blob: 842582f52383054f7fd74b64971c94c74d6fe528 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400197 spv::Id createSpvConstant(const glslang::TIntermTyped&);
198 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600199 bool isTrivialLeaf(const glslang::TIntermTyped* node);
200 bool isTrivial(const glslang::TIntermTyped* node);
201 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500202#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800203 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500204#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700205 void addPre13Extension(const char* ext)
206 {
207 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
208 builder.addExtension(ext);
209 }
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich121853f2017-05-31 17:11:16 -0600211 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600213 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700214 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 int sequenceDepth;
216
Lei Zhang17535f72016-05-04 15:55:59 -0400217 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400218
John Kessenich140f3df2015-06-26 16:58:36 -0600219 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
220 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700221 bool inEntryPoint;
222 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700223 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 -0700224 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600225 const glslang::TIntermediate* glslangIntermediate;
226 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800227 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600228
John Kessenich2f273362015-07-18 22:34:27 -0600229 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600230 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600231 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700232 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700233 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
234 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600237};
238
239//
240// Helper functions for translating glslang representations to SPIR-V enumerants.
241//
242
243// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700244spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600245{
John Kessenich66e2faf2016-03-12 18:34:36 -0700246 switch (source) {
247 case glslang::EShSourceGlsl:
248 switch (profile) {
249 case ENoProfile:
250 case ECoreProfile:
251 case ECompatibilityProfile:
252 return spv::SourceLanguageGLSL;
253 case EEsProfile:
254 return spv::SourceLanguageESSL;
255 default:
256 return spv::SourceLanguageUnknown;
257 }
258 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600259 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
261 return spv::SourceLanguageUnknown;
262 }
263}
264
265// Translate glslang language (stage) to SPIR-V execution model.
266spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
267{
268 switch (stage) {
269 case EShLangVertex: return spv::ExecutionModelVertex;
270 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
271 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
272 case EShLangGeometry: return spv::ExecutionModelGeometry;
273 case EShLangFragment: return spv::ExecutionModelFragment;
274 case EShLangCompute: return spv::ExecutionModelGLCompute;
275 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700276 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600277 return spv::ExecutionModelFragment;
278 }
279}
280
John Kessenich140f3df2015-06-26 16:58:36 -0600281// Translate glslang sampler type to SPIR-V dimensionality.
282spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
283{
284 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700285 case glslang::Esd1D: return spv::Dim1D;
286 case glslang::Esd2D: return spv::Dim2D;
287 case glslang::Esd3D: return spv::Dim3D;
288 case glslang::EsdCube: return spv::DimCube;
289 case glslang::EsdRect: return spv::DimRect;
290 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700291 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return spv::Dim2D;
295 }
296}
297
John Kessenichf6640762016-08-01 19:44:00 -0600298// Translate glslang precision to SPIR-V precision decorations.
299spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600300{
John Kessenichf6640762016-08-01 19:44:00 -0600301 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700302 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600303 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::NoPrecision;
306 }
307}
308
John Kessenichf6640762016-08-01 19:44:00 -0600309// Translate glslang type to SPIR-V precision decorations.
310spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
311{
312 return TranslatePrecisionDecoration(type.getQualifier().precision);
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600316spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600317{
318 if (type.getBasicType() == glslang::EbtBlock) {
319 switch (type.getQualifier().storage) {
320 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600321 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::EvqVaryingIn: return spv::DecorationBlock;
323 case glslang::EvqVaryingOut: return spv::DecorationBlock;
324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 break;
327 }
328 }
329
John Kessenich4016e382016-07-15 11:53:56 -0600330 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600331}
332
Rex Xu1da878f2016-02-21 20:59:01 +0800333// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500334void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800335{
Jeff Bolz36831c92018-09-05 10:11:41 -0500336 if (!useVulkanMemoryModel) {
337 if (qualifier.coherent)
338 memory.push_back(spv::DecorationCoherent);
339 if (qualifier.volatil) {
340 memory.push_back(spv::DecorationVolatile);
341 memory.push_back(spv::DecorationCoherent);
342 }
John Kessenich14b85d32018-06-04 15:36:03 -0600343 }
Rex Xu1da878f2016-02-21 20:59:01 +0800344 if (qualifier.restrict)
345 memory.push_back(spv::DecorationRestrict);
346 if (qualifier.readonly)
347 memory.push_back(spv::DecorationNonWritable);
348 if (qualifier.writeonly)
349 memory.push_back(spv::DecorationNonReadable);
350}
351
John Kessenich140f3df2015-06-26 16:58:36 -0600352// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700353spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
355 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700356 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600357 case glslang::ElmRowMajor:
358 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600360 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700361 default:
362 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 }
365 } else {
366 switch (type.getBasicType()) {
367 default:
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 break;
370 case glslang::EbtBlock:
371 switch (type.getQualifier().storage) {
372 case glslang::EvqUniform:
373 case glslang::EvqBuffer:
374 switch (type.getQualifier().layoutPacking) {
375 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
377 default:
John Kessenich4016e382016-07-15 11:53:56 -0600378 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 }
380 case glslang::EvqVaryingIn:
381 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 }
388 }
389 }
390}
391
392// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700394// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800395spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
Rex Xubbceed72016-05-21 09:40:44 +0800397 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700398 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800400 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700402 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800404#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800405 else if (qualifier.explicitInterp) {
406 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800407 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800408 }
Rex Xu9d93a232016-05-05 12:30:44 +0800409#endif
Rex Xubbceed72016-05-21 09:40:44 +0800410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800412}
413
414// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600415// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800416// should be applied.
417spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
418{
419 if (qualifier.patch)
420 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700423 else if (qualifier.sample) {
424 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700426 } else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600428}
429
John Kessenich92187592016-02-01 13:45:25 -0700430// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700431spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700433 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600434 return spv::DecorationInvariant;
435 else
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437}
438
qining9220dbb2016-05-04 17:34:38 -0400439// If glslang type is noContraction, return SPIR-V NoContraction decoration.
440spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
441{
442 if (qualifier.noContraction)
443 return spv::DecorationNoContraction;
444 else
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400446}
447
John Kessenich5611c6d2018-04-05 11:25:02 -0600448// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
449spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
450{
451 if (qualifier.isNonUniform()) {
452 builder.addExtension("SPV_EXT_descriptor_indexing");
453 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
454 return spv::DecorationNonUniformEXT;
455 } else
456 return spv::DecorationMax;
457}
458
Jeff Bolz36831c92018-09-05 10:11:41 -0500459spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
460{
461 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
462 return spv::MemoryAccessMaskNone;
463 }
464 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
465 if (coherentFlags.volatil ||
466 coherentFlags.coherent ||
467 coherentFlags.devicecoherent ||
468 coherentFlags.queuefamilycoherent ||
469 coherentFlags.workgroupcoherent ||
470 coherentFlags.subgroupcoherent) {
471 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
472 spv::MemoryAccessMakePointerVisibleKHRMask;
473 }
474 if (coherentFlags.nonprivate) {
475 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
476 }
477 if (coherentFlags.volatil) {
478 mask = mask | spv::MemoryAccessVolatileMask;
479 }
480 if (mask != spv::MemoryAccessMaskNone) {
481 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
482 }
483 return mask;
484}
485
486spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
487{
488 if (!glslangIntermediate->usingVulkanMemoryModel()) {
489 return spv::ImageOperandsMaskNone;
490 }
491 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
492 if (coherentFlags.volatil ||
493 coherentFlags.coherent ||
494 coherentFlags.devicecoherent ||
495 coherentFlags.queuefamilycoherent ||
496 coherentFlags.workgroupcoherent ||
497 coherentFlags.subgroupcoherent) {
498 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
499 spv::ImageOperandsMakeTexelVisibleKHRMask;
500 }
501 if (coherentFlags.nonprivate) {
502 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
503 }
504 if (coherentFlags.volatil) {
505 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
506 }
507 if (mask != spv::ImageOperandsMaskNone) {
508 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
509 }
510 return mask;
511}
512
513spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
514{
515 spv::Builder::AccessChain::CoherentFlags flags;
516 flags.coherent = type.getQualifier().coherent;
517 flags.devicecoherent = type.getQualifier().devicecoherent;
518 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
519 // shared variables are implicitly workgroupcoherent in GLSL.
520 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
521 type.getQualifier().storage == glslang::EvqShared;
522 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
523 // *coherent variables are implicitly nonprivate in GLSL
524 flags.nonprivate = type.getQualifier().nonprivate ||
525 type.getQualifier().subgroupcoherent ||
526 type.getQualifier().workgroupcoherent ||
527 type.getQualifier().queuefamilycoherent ||
528 type.getQualifier().devicecoherent ||
529 type.getQualifier().coherent;
530 flags.volatil = type.getQualifier().volatil;
531 flags.isImage = type.getBasicType() == glslang::EbtSampler;
532 return flags;
533}
534
535spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
536{
537 spv::Scope scope;
538 if (coherentFlags.coherent) {
539 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
540 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
541 } else if (coherentFlags.devicecoherent) {
542 scope = spv::ScopeDevice;
543 } else if (coherentFlags.queuefamilycoherent) {
544 scope = spv::ScopeQueueFamilyKHR;
545 } else if (coherentFlags.workgroupcoherent) {
546 scope = spv::ScopeWorkgroup;
547 } else if (coherentFlags.subgroupcoherent) {
548 scope = spv::ScopeSubgroup;
549 } else {
550 scope = spv::ScopeMax;
551 }
552 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
553 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
554 }
555 return scope;
556}
557
David Netoa901ffe2016-06-08 14:11:40 +0100558// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
559// associated capabilities when required. For some built-in variables, a capability
560// is generated only when using the variable in an executable instruction, but not when
561// just declaring a struct member variable with it. This is true for PointSize,
562// ClipDistance, and CullDistance.
563spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600564{
565 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700566 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600567 // Defer adding the capability until the built-in is actually used.
568 if (! memberDeclaration) {
569 switch (glslangIntermediate->getStage()) {
570 case EShLangGeometry:
571 builder.addCapability(spv::CapabilityGeometryPointSize);
572 break;
573 case EShLangTessControl:
574 case EShLangTessEvaluation:
575 builder.addCapability(spv::CapabilityTessellationPointSize);
576 break;
577 default:
578 break;
579 }
John Kessenich92187592016-02-01 13:45:25 -0700580 }
581 return spv::BuiltInPointSize;
582
John Kessenichebb50532016-05-16 19:22:05 -0600583 // These *Distance capabilities logically belong here, but if the member is declared and
584 // then never used, consumers of SPIR-V prefer the capability not be declared.
585 // They are now generated when used, rather than here when declared.
586 // Potentially, the specification should be more clear what the minimum
587 // use needed is to trigger the capability.
588 //
John Kessenich92187592016-02-01 13:45:25 -0700589 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100590 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800591 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700592 return spv::BuiltInClipDistance;
593
594 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100595 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800596 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700597 return spv::BuiltInCullDistance;
598
599 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600600 builder.addCapability(spv::CapabilityMultiViewport);
601 if (glslangIntermediate->getStage() == EShLangVertex ||
602 glslangIntermediate->getStage() == EShLangTessControl ||
603 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800604
John Kessenichba6a3c22017-09-13 13:22:50 -0600605 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
606 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800607 }
John Kessenich92187592016-02-01 13:45:25 -0700608 return spv::BuiltInViewportIndex;
609
John Kessenich5e801132016-02-15 11:09:46 -0700610 case glslang::EbvSampleId:
611 builder.addCapability(spv::CapabilitySampleRateShading);
612 return spv::BuiltInSampleId;
613
614 case glslang::EbvSamplePosition:
615 builder.addCapability(spv::CapabilitySampleRateShading);
616 return spv::BuiltInSamplePosition;
617
618 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700619 return spv::BuiltInSampleMask;
620
John Kessenich78a45572016-07-08 14:05:15 -0600621 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600622 builder.addCapability(spv::CapabilityGeometry);
623 if (glslangIntermediate->getStage() == EShLangVertex ||
624 glslangIntermediate->getStage() == EShLangTessControl ||
625 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800626
John Kessenichba6a3c22017-09-13 13:22:50 -0600627 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
628 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800629 }
John Kessenich78a45572016-07-08 14:05:15 -0600630 return spv::BuiltInLayer;
631
John Kessenich140f3df2015-06-26 16:58:36 -0600632 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600633 case glslang::EbvVertexId: return spv::BuiltInVertexId;
634 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700635 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
636 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800637
John Kessenichda581a22015-10-14 14:10:30 -0600638 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700639 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800640 builder.addCapability(spv::CapabilityDrawParameters);
641 return spv::BuiltInBaseVertex;
642
John Kessenichda581a22015-10-14 14:10:30 -0600643 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700644 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800645 builder.addCapability(spv::CapabilityDrawParameters);
646 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200647
John Kessenichda581a22015-10-14 14:10:30 -0600648 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700649 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800650 builder.addCapability(spv::CapabilityDrawParameters);
651 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200652
653 case glslang::EbvPrimitiveId:
654 if (glslangIntermediate->getStage() == EShLangFragment)
655 builder.addCapability(spv::CapabilityGeometry);
656 return spv::BuiltInPrimitiveId;
657
Rex Xu37cdcee2017-06-29 17:46:34 +0800658 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800659 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
660 builder.addCapability(spv::CapabilityStencilExportEXT);
661 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800662
John Kessenich140f3df2015-06-26 16:58:36 -0600663 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600664 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
665 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
666 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
667 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
668 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
669 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
670 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600671 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
672 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
673 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
674 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
675 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
676 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
677 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
678 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800679
Rex Xu574ab042016-04-14 16:53:07 +0800680 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800681 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800682 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
683 return spv::BuiltInSubgroupSize;
684
Rex Xu574ab042016-04-14 16:53:07 +0800685 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800686 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800687 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
688 return spv::BuiltInSubgroupLocalInvocationId;
689
Rex Xu574ab042016-04-14 16:53:07 +0800690 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800691 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
692 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
693 return spv::BuiltInSubgroupEqMaskKHR;
694
Rex Xu574ab042016-04-14 16:53:07 +0800695 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800696 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
697 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
698 return spv::BuiltInSubgroupGeMaskKHR;
699
Rex Xu574ab042016-04-14 16:53:07 +0800700 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800701 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
702 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
703 return spv::BuiltInSubgroupGtMaskKHR;
704
Rex Xu574ab042016-04-14 16:53:07 +0800705 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800706 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
707 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
708 return spv::BuiltInSubgroupLeMaskKHR;
709
Rex Xu574ab042016-04-14 16:53:07 +0800710 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800711 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
712 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
713 return spv::BuiltInSubgroupLtMaskKHR;
714
John Kessenich66011cb2018-03-06 16:12:04 -0700715 case glslang::EbvNumSubgroups:
716 builder.addCapability(spv::CapabilityGroupNonUniform);
717 return spv::BuiltInNumSubgroups;
718
719 case glslang::EbvSubgroupID:
720 builder.addCapability(spv::CapabilityGroupNonUniform);
721 return spv::BuiltInSubgroupId;
722
723 case glslang::EbvSubgroupSize2:
724 builder.addCapability(spv::CapabilityGroupNonUniform);
725 return spv::BuiltInSubgroupSize;
726
727 case glslang::EbvSubgroupInvocation2:
728 builder.addCapability(spv::CapabilityGroupNonUniform);
729 return spv::BuiltInSubgroupLocalInvocationId;
730
731 case glslang::EbvSubgroupEqMask2:
732 builder.addCapability(spv::CapabilityGroupNonUniform);
733 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
734 return spv::BuiltInSubgroupEqMask;
735
736 case glslang::EbvSubgroupGeMask2:
737 builder.addCapability(spv::CapabilityGroupNonUniform);
738 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
739 return spv::BuiltInSubgroupGeMask;
740
741 case glslang::EbvSubgroupGtMask2:
742 builder.addCapability(spv::CapabilityGroupNonUniform);
743 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
744 return spv::BuiltInSubgroupGtMask;
745
746 case glslang::EbvSubgroupLeMask2:
747 builder.addCapability(spv::CapabilityGroupNonUniform);
748 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
749 return spv::BuiltInSubgroupLeMask;
750
751 case glslang::EbvSubgroupLtMask2:
752 builder.addCapability(spv::CapabilityGroupNonUniform);
753 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
754 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800755#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800756 case glslang::EbvBaryCoordNoPersp:
757 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
758 return spv::BuiltInBaryCoordNoPerspAMD;
759
760 case glslang::EbvBaryCoordNoPerspCentroid:
761 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
762 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
763
764 case glslang::EbvBaryCoordNoPerspSample:
765 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
766 return spv::BuiltInBaryCoordNoPerspSampleAMD;
767
768 case glslang::EbvBaryCoordSmooth:
769 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
770 return spv::BuiltInBaryCoordSmoothAMD;
771
772 case glslang::EbvBaryCoordSmoothCentroid:
773 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
774 return spv::BuiltInBaryCoordSmoothCentroidAMD;
775
776 case glslang::EbvBaryCoordSmoothSample:
777 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
778 return spv::BuiltInBaryCoordSmoothSampleAMD;
779
780 case glslang::EbvBaryCoordPullModel:
781 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
782 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800783#endif
chaoc771d89f2017-01-13 01:10:53 -0800784
John Kessenich6c8aaac2017-02-27 01:20:51 -0700785 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700786 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700787 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700788 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700789
790 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700791 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700792 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700793 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700794
chaoc771d89f2017-01-13 01:10:53 -0800795#ifdef NV_EXTENSIONS
796 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800797 if (!memberDeclaration) {
798 builder.addExtension(spv::E_SPV_NV_viewport_array2);
799 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
800 }
chaoc771d89f2017-01-13 01:10:53 -0800801 return spv::BuiltInViewportMaskNV;
802 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800803 if (!memberDeclaration) {
804 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
805 builder.addCapability(spv::CapabilityShaderStereoViewNV);
806 }
chaoc771d89f2017-01-13 01:10:53 -0800807 return spv::BuiltInSecondaryPositionNV;
808 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800809 if (!memberDeclaration) {
810 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
811 builder.addCapability(spv::CapabilityShaderStereoViewNV);
812 }
chaoc771d89f2017-01-13 01:10:53 -0800813 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800814 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800815 if (!memberDeclaration) {
816 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
817 builder.addCapability(spv::CapabilityPerViewAttributesNV);
818 }
chaocdf3956c2017-02-14 14:52:34 -0800819 return spv::BuiltInPositionPerViewNV;
820 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800821 if (!memberDeclaration) {
822 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
823 builder.addCapability(spv::CapabilityPerViewAttributesNV);
824 }
chaocdf3956c2017-02-14 14:52:34 -0800825 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700826 case glslang::EbvFragFullyCoveredNV:
827 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
828 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
829 return spv::BuiltInFullyCoveredEXT;
Chao Chen9eada4b2018-09-19 11:39:56 -0700830 case glslang::EbvBaryCoordNV:
831 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
832 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
833 return spv::BuiltInBaryCoordNV;
834 case glslang::EbvBaryCoordNoPerspNV:
835 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
836 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
837 return spv::BuiltInBaryCoordNoPerspNV;
chaoc771d89f2017-01-13 01:10:53 -0800838#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800839 default:
840 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600841 }
842}
843
Rex Xufc618912015-09-09 16:42:49 +0800844// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700845spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800846{
847 assert(type.getBasicType() == glslang::EbtSampler);
848
John Kessenich5d0fa972016-02-15 11:57:00 -0700849 // Check for capabilities
850 switch (type.getQualifier().layoutFormat) {
851 case glslang::ElfRg32f:
852 case glslang::ElfRg16f:
853 case glslang::ElfR11fG11fB10f:
854 case glslang::ElfR16f:
855 case glslang::ElfRgba16:
856 case glslang::ElfRgb10A2:
857 case glslang::ElfRg16:
858 case glslang::ElfRg8:
859 case glslang::ElfR16:
860 case glslang::ElfR8:
861 case glslang::ElfRgba16Snorm:
862 case glslang::ElfRg16Snorm:
863 case glslang::ElfRg8Snorm:
864 case glslang::ElfR16Snorm:
865 case glslang::ElfR8Snorm:
866
867 case glslang::ElfRg32i:
868 case glslang::ElfRg16i:
869 case glslang::ElfRg8i:
870 case glslang::ElfR16i:
871 case glslang::ElfR8i:
872
873 case glslang::ElfRgb10a2ui:
874 case glslang::ElfRg32ui:
875 case glslang::ElfRg16ui:
876 case glslang::ElfRg8ui:
877 case glslang::ElfR16ui:
878 case glslang::ElfR8ui:
879 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
880 break;
881
882 default:
883 break;
884 }
885
886 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800887 switch (type.getQualifier().layoutFormat) {
888 case glslang::ElfNone: return spv::ImageFormatUnknown;
889 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
890 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
891 case glslang::ElfR32f: return spv::ImageFormatR32f;
892 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
893 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
894 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
895 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
896 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
897 case glslang::ElfR16f: return spv::ImageFormatR16f;
898 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
899 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
900 case glslang::ElfRg16: return spv::ImageFormatRg16;
901 case glslang::ElfRg8: return spv::ImageFormatRg8;
902 case glslang::ElfR16: return spv::ImageFormatR16;
903 case glslang::ElfR8: return spv::ImageFormatR8;
904 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
905 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
906 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
907 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
908 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
909 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
910 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
911 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
912 case glslang::ElfR32i: return spv::ImageFormatR32i;
913 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
914 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
915 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
916 case glslang::ElfR16i: return spv::ImageFormatR16i;
917 case glslang::ElfR8i: return spv::ImageFormatR8i;
918 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
919 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
920 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
921 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
922 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
923 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
924 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
925 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
926 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
927 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800929 }
930}
931
John Kesseniche18fd202018-01-30 11:01:39 -0700932spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800933{
John Kesseniche18fd202018-01-30 11:01:39 -0700934 if (selectionNode.getFlatten())
935 return spv::SelectionControlFlattenMask;
936 if (selectionNode.getDontFlatten())
937 return spv::SelectionControlDontFlattenMask;
938 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800939}
940
John Kesseniche18fd202018-01-30 11:01:39 -0700941spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600942{
John Kesseniche18fd202018-01-30 11:01:39 -0700943 if (switchNode.getFlatten())
944 return spv::SelectionControlFlattenMask;
945 if (switchNode.getDontFlatten())
946 return spv::SelectionControlDontFlattenMask;
947 return spv::SelectionControlMaskNone;
948}
949
John Kessenicha2858d92018-01-31 08:11:18 -0700950// return a non-0 dependency if the dependency argument must be set
951spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
952 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700953{
954 spv::LoopControlMask control = spv::LoopControlMaskNone;
955
956 if (loopNode.getDontUnroll())
957 control = control | spv::LoopControlDontUnrollMask;
958 if (loopNode.getUnroll())
959 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700960 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700961 control = control | spv::LoopControlDependencyInfiniteMask;
962 else if (loopNode.getLoopDependency() > 0) {
963 control = control | spv::LoopControlDependencyLengthMask;
964 dependencyLength = loopNode.getLoopDependency();
965 }
John Kesseniche18fd202018-01-30 11:01:39 -0700966
967 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600968}
969
John Kessenicha5c5fb62017-05-05 05:09:58 -0600970// Translate glslang type to SPIR-V storage class.
971spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
972{
973 if (type.getQualifier().isPipeInput())
974 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600975 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600976 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600977
978 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
979 type.getQualifier().storage == glslang::EvqUniform) {
980 if (type.getBasicType() == glslang::EbtAtomicUint)
981 return spv::StorageClassAtomicCounter;
982 if (type.containsOpaque())
983 return spv::StorageClassUniformConstant;
984 }
985
986 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700987 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600988 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600989 }
990
991 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600992 if (type.getQualifier().layoutPushConstant)
993 return spv::StorageClassPushConstant;
994 if (type.getBasicType() == glslang::EbtBlock)
995 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600996 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600997 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600998
999 switch (type.getQualifier().storage) {
1000 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1001 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1002 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1003 case glslang::EvqTemporary: return spv::StorageClassFunction;
1004 default:
1005 assert(0);
1006 break;
1007 }
1008
1009 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001010}
1011
John Kessenich5611c6d2018-04-05 11:25:02 -06001012// Add capabilities pertaining to how an array is indexed.
1013void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1014 const glslang::TType& indexType)
1015{
1016 if (indexType.getQualifier().isNonUniform()) {
1017 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001018 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001019 if (baseType.getBasicType() == glslang::EbtSampler) {
1020 if (baseType.getQualifier().hasAttachment())
1021 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1022 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1023 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1024 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1025 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1026 else if (baseType.isImage())
1027 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1028 else if (baseType.isTexture())
1029 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1030 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1031 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1032 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1033 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1034 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1035 }
1036 } else {
1037 // assume a dynamically uniform index
1038 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001039 if (baseType.getQualifier().hasAttachment()) {
1040 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001041 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001042 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1043 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001044 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001045 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1046 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001047 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001048 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001049 }
1050 }
1051}
1052
qining25262b32016-05-06 17:25:16 -04001053// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001054// descriptor set.
1055bool IsDescriptorResource(const glslang::TType& type)
1056{
John Kessenichf7497e22016-03-08 21:36:22 -07001057 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001058 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -07001059 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001060
1061 // non block...
1062 // basically samplerXXX/subpass/sampler/texture are all included
1063 // if they are the global-scope-class, not the function parameter
1064 // (or local, if they ever exist) class.
1065 if (type.getBasicType() == glslang::EbtSampler)
1066 return type.getQualifier().isUniformOrBuffer();
1067
1068 // None of the above.
1069 return false;
1070}
1071
John Kesseniche0b6cad2015-12-24 10:30:13 -07001072void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1073{
1074 if (child.layoutMatrix == glslang::ElmNone)
1075 child.layoutMatrix = parent.layoutMatrix;
1076
1077 if (parent.invariant)
1078 child.invariant = true;
1079 if (parent.nopersp)
1080 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001081#ifdef AMD_EXTENSIONS
1082 if (parent.explicitInterp)
1083 child.explicitInterp = true;
1084#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001085 if (parent.flat)
1086 child.flat = true;
1087 if (parent.centroid)
1088 child.centroid = true;
1089 if (parent.patch)
1090 child.patch = true;
1091 if (parent.sample)
1092 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001093 if (parent.coherent)
1094 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001095 if (parent.devicecoherent)
1096 child.devicecoherent = true;
1097 if (parent.queuefamilycoherent)
1098 child.queuefamilycoherent = true;
1099 if (parent.workgroupcoherent)
1100 child.workgroupcoherent = true;
1101 if (parent.subgroupcoherent)
1102 child.subgroupcoherent = true;
1103 if (parent.nonprivate)
1104 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001105 if (parent.volatil)
1106 child.volatil = true;
1107 if (parent.restrict)
1108 child.restrict = true;
1109 if (parent.readonly)
1110 child.readonly = true;
1111 if (parent.writeonly)
1112 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001113}
1114
John Kessenichf2b7f332016-09-01 17:05:23 -06001115bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001116{
John Kessenich7b9fa252016-01-21 18:56:57 -07001117 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001118 // - struct members might inherit from a struct declaration
1119 // (note that non-block structs don't explicitly inherit,
1120 // only implicitly, meaning no decoration involved)
1121 // - affect decorations on the struct members
1122 // (note smooth does not, and expecting something like volatile
1123 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001124 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001125 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001126}
1127
John Kessenich140f3df2015-06-26 16:58:36 -06001128//
1129// Implement the TGlslangToSpvTraverser class.
1130//
1131
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001132TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001133 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1134 : TIntermTraverser(true, false, true),
1135 options(options),
1136 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001137 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001138 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001139 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001140 glslangIntermediate(glslangIntermediate)
1141{
1142 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1143
1144 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001145 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1146 glslangIntermediate->getVersion());
1147
John Kessenich121853f2017-05-31 17:11:16 -06001148 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001149 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001150 builder.setSourceFile(glslangIntermediate->getSourceFile());
1151
1152 // Set the source shader's text. If for SPV version 1.0, include
1153 // a preamble in comments stating the OpModuleProcessed instructions.
1154 // Otherwise, emit those as actual instructions.
1155 std::string text;
1156 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1157 for (int p = 0; p < (int)processes.size(); ++p) {
1158 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1159 text.append("// OpModuleProcessed ");
1160 text.append(processes[p]);
1161 text.append("\n");
1162 } else
1163 builder.addModuleProcessed(processes[p]);
1164 }
1165 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1166 text.append("#line 1\n");
1167 text.append(glslangIntermediate->getSourceText());
1168 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001169 }
John Kessenich140f3df2015-06-26 16:58:36 -06001170 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001171 if (glslangIntermediate->usingVulkanMemoryModel()) {
1172 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1173 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1174 } else {
1175 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1176 }
John Kessenicheee9d532016-09-19 18:09:30 -06001177 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1178 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001181 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1182 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001183 builder.addSourceExtension(it->c_str());
1184
1185 // Add the top-level modes for this shader.
1186
John Kessenich92187592016-02-01 13:45:25 -07001187 if (glslangIntermediate->getXfbMode()) {
1188 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001189 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001190 }
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 unsigned int mode;
1193 switch (glslangIntermediate->getStage()) {
1194 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001195 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001196 break;
1197
steve-lunarge7412492017-03-23 11:56:07 -06001198 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001199 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001200 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001201
steve-lunarge7412492017-03-23 11:56:07 -06001202 glslang::TLayoutGeometry primitive;
1203
1204 if (glslangIntermediate->getStage() == EShLangTessControl) {
1205 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1206 primitive = glslangIntermediate->getOutputPrimitive();
1207 } else {
1208 primitive = glslangIntermediate->getInputPrimitive();
1209 }
1210
1211 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001212 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1213 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1214 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001215 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001216 }
John Kessenich4016e382016-07-15 11:53:56 -06001217 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001218 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1219
John Kesseniche6903322015-10-13 16:29:02 -06001220 switch (glslangIntermediate->getVertexSpacing()) {
1221 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1222 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1223 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001224 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001225 }
John Kessenich4016e382016-07-15 11:53:56 -06001226 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001227 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1228
1229 switch (glslangIntermediate->getVertexOrder()) {
1230 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1231 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001232 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001233 }
John Kessenich4016e382016-07-15 11:53:56 -06001234 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001235 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1236
1237 if (glslangIntermediate->getPointMode())
1238 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001239 break;
1240
1241 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001242 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001243 switch (glslangIntermediate->getInputPrimitive()) {
1244 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1245 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1246 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001247 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001248 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001249 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001250 }
John Kessenich4016e382016-07-15 11:53:56 -06001251 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001253
John Kessenich140f3df2015-06-26 16:58:36 -06001254 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1255
1256 switch (glslangIntermediate->getOutputPrimitive()) {
1257 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1258 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1259 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001260 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
John Kessenich4016e382016-07-15 11:53:56 -06001262 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001263 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1264 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1265 break;
1266
1267 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001268 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001269 if (glslangIntermediate->getPixelCenterInteger())
1270 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001271
John Kessenich140f3df2015-06-26 16:58:36 -06001272 if (glslangIntermediate->getOriginUpperLeft())
1273 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001274 else
1275 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001276
1277 if (glslangIntermediate->getEarlyFragmentTests())
1278 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1279
chaocc1204522017-06-30 17:14:30 -07001280 if (glslangIntermediate->getPostDepthCoverage()) {
1281 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1282 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1283 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1284 }
1285
John Kesseniche6903322015-10-13 16:29:02 -06001286 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001287 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1288 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001289 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001290 }
John Kessenich4016e382016-07-15 11:53:56 -06001291 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001292 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1293
1294 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1295 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001296 break;
1297
1298 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001299 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001300 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1301 glslangIntermediate->getLocalSize(1),
1302 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001303#ifdef NV_EXTENSIONS
1304 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1305 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1306 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1307 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1308 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1309 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1310 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1311 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1312 }
1313#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001314 break;
1315
1316 default:
1317 break;
1318 }
John Kessenich140f3df2015-06-26 16:58:36 -06001319}
1320
John Kessenichfca82622016-11-26 13:23:20 -07001321// Finish creating SPV, after the traversal is complete.
1322void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001323{
John Kessenichf04c51b2018-08-03 15:56:12 -06001324 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001325 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001326 builder.setBuildPoint(shaderEntry->getLastBlock());
1327 builder.leaveFunction();
1328 }
1329
John Kessenich7ba63412015-12-20 17:37:07 -07001330 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001331 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1332 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001333
John Kessenichf04c51b2018-08-03 15:56:12 -06001334 // Add capabilities, extensions, remove unneeded decorations, etc.,
1335 // based on the resulting SPIR-V.
1336 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001337}
1338
John Kessenichfca82622016-11-26 13:23:20 -07001339// Write the SPV into 'out'.
1340void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001341{
John Kessenichfca82622016-11-26 13:23:20 -07001342 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001343}
1344
1345//
1346// Implement the traversal functions.
1347//
1348// Return true from interior nodes to have the external traversal
1349// continue on to children. Return false if children were
1350// already processed.
1351//
1352
1353//
qining25262b32016-05-06 17:25:16 -04001354// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001355// - uniform/input reads
1356// - output writes
1357// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1358// - something simple that degenerates into the last bullet
1359//
1360void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1361{
qining75d1d802016-04-06 14:42:01 -04001362 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1363 if (symbol->getType().getQualifier().isSpecConstant())
1364 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366 // getSymbolId() will set up all the IO decorations on the first call.
1367 // Formal function parameters were mapped during makeFunctions().
1368 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001369
1370 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1371 if (builder.isPointer(id)) {
1372 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001373 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1374 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1375 iOSet.insert(id);
1376 }
John Kessenich7ba63412015-12-20 17:37:07 -07001377 }
1378
1379 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001380 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001381 // Prepare to generate code for the access
1382
1383 // L-value chains will be computed left to right. We're on the symbol now,
1384 // which is the left-most part of the access chain, so now is "clear" time,
1385 // followed by setting the base.
1386 builder.clearAccessChain();
1387
1388 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001389 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001390 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001391 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001392 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001393 // These are also pure R-values.
1394 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001395 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001396 builder.setAccessChainRValue(id);
1397 else
1398 builder.setAccessChainLValue(id);
1399 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001400
1401 // Process linkage-only nodes for any special additional interface work.
1402 if (linkageOnly) {
1403 if (glslangIntermediate->getHlslFunctionality1()) {
1404 // Map implicit counter buffers to their originating buffers, which should have been
1405 // seen by now, given earlier pruning of unused counters, and preservation of order
1406 // of declaration.
1407 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1408 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1409 // Save possible originating buffers for counter buffers, keyed by
1410 // making the potential counter-buffer name.
1411 std::string keyName = symbol->getName().c_str();
1412 keyName = glslangIntermediate->addCounterBufferName(keyName);
1413 counterOriginator[keyName] = symbol;
1414 } else {
1415 // Handle a counter buffer, by finding the saved originating buffer.
1416 std::string keyName = symbol->getName().c_str();
1417 auto it = counterOriginator.find(keyName);
1418 if (it != counterOriginator.end()) {
1419 id = getSymbolId(it->second);
1420 if (id != spv::NoResult) {
1421 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001422 if (counterId != spv::NoResult) {
1423 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001424 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001425 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001426 }
1427 }
1428 }
1429 }
1430 }
1431 }
John Kessenich140f3df2015-06-26 16:58:36 -06001432}
1433
1434bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1435{
John Kesseniche485c7a2017-05-31 18:50:53 -06001436 builder.setLine(node->getLoc().line);
1437
qining40887662016-04-03 22:20:42 -04001438 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1439 if (node->getType().getQualifier().isSpecConstant())
1440 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1441
John Kessenich140f3df2015-06-26 16:58:36 -06001442 // First, handle special cases
1443 switch (node->getOp()) {
1444 case glslang::EOpAssign:
1445 case glslang::EOpAddAssign:
1446 case glslang::EOpSubAssign:
1447 case glslang::EOpMulAssign:
1448 case glslang::EOpVectorTimesMatrixAssign:
1449 case glslang::EOpVectorTimesScalarAssign:
1450 case glslang::EOpMatrixTimesScalarAssign:
1451 case glslang::EOpMatrixTimesMatrixAssign:
1452 case glslang::EOpDivAssign:
1453 case glslang::EOpModAssign:
1454 case glslang::EOpAndAssign:
1455 case glslang::EOpInclusiveOrAssign:
1456 case glslang::EOpExclusiveOrAssign:
1457 case glslang::EOpLeftShiftAssign:
1458 case glslang::EOpRightShiftAssign:
1459 // A bin-op assign "a += b" means the same thing as "a = a + b"
1460 // where a is evaluated before b. For a simple assignment, GLSL
1461 // says to evaluate the left before the right. So, always, left
1462 // node then right node.
1463 {
1464 // get the left l-value, save it away
1465 builder.clearAccessChain();
1466 node->getLeft()->traverse(this);
1467 spv::Builder::AccessChain lValue = builder.getAccessChain();
1468
1469 // evaluate the right
1470 builder.clearAccessChain();
1471 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001472 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001473
1474 if (node->getOp() != glslang::EOpAssign) {
1475 // the left is also an r-value
1476 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001477 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001478
1479 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001480 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001481 TranslateNoContractionDecoration(node->getType().getQualifier()),
1482 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001483 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001484 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1485 node->getType().getBasicType());
1486
1487 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001488 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001489 }
1490
1491 // store the result
1492 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001493 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001494
1495 // assignments are expressions having an rValue after they are evaluated...
1496 builder.clearAccessChain();
1497 builder.setAccessChainRValue(rValue);
1498 }
1499 return false;
1500 case glslang::EOpIndexDirect:
1501 case glslang::EOpIndexDirectStruct:
1502 {
1503 // Get the left part of the access chain.
1504 node->getLeft()->traverse(this);
1505
1506 // Add the next element in the chain
1507
David Netoa901ffe2016-06-08 14:11:40 +01001508 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001509 if (! node->getLeft()->getType().isArray() &&
1510 node->getLeft()->getType().isVector() &&
1511 node->getOp() == glslang::EOpIndexDirect) {
1512 // This is essentially a hard-coded vector swizzle of size 1,
1513 // so short circuit the access-chain stuff with a swizzle.
1514 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001515 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001516 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001517 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001518 int spvIndex = glslangIndex;
1519 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1520 node->getOp() == glslang::EOpIndexDirectStruct)
1521 {
1522 // This may be, e.g., an anonymous block-member selection, which generally need
1523 // index remapping due to hidden members in anonymous blocks.
1524 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1525 assert(remapper.size() > 0);
1526 spvIndex = remapper[glslangIndex];
1527 }
John Kessenichebb50532016-05-16 19:22:05 -06001528
David Netoa901ffe2016-06-08 14:11:40 +01001529 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001530 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001531
1532 // Add capabilities here for accessing PointSize and clip/cull distance.
1533 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001534 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001535 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001536 }
1537 }
1538 return false;
1539 case glslang::EOpIndexIndirect:
1540 {
1541 // Structure or array or vector indirection.
1542 // Will use native SPIR-V access-chain for struct and array indirection;
1543 // matrices are arrays of vectors, so will also work for a matrix.
1544 // Will use the access chain's 'component' for variable index into a vector.
1545
1546 // This adapter is building access chains left to right.
1547 // Set up the access chain to the left.
1548 node->getLeft()->traverse(this);
1549
1550 // save it so that computing the right side doesn't trash it
1551 spv::Builder::AccessChain partial = builder.getAccessChain();
1552
1553 // compute the next index in the chain
1554 builder.clearAccessChain();
1555 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001556 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001557
John Kessenich5611c6d2018-04-05 11:25:02 -06001558 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1559
John Kessenich140f3df2015-06-26 16:58:36 -06001560 // restore the saved access chain
1561 builder.setAccessChain(partial);
1562
1563 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001564 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001565 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001566 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001567 }
1568 return false;
1569 case glslang::EOpVectorSwizzle:
1570 {
1571 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001572 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001574 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
1576 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001577 case glslang::EOpMatrixSwizzle:
1578 logger->missingFunctionality("matrix swizzle");
1579 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001580 case glslang::EOpLogicalOr:
1581 case glslang::EOpLogicalAnd:
1582 {
1583
1584 // These may require short circuiting, but can sometimes be done as straight
1585 // binary operations. The right operand must be short circuited if it has
1586 // side effects, and should probably be if it is complex.
1587 if (isTrivial(node->getRight()->getAsTyped()))
1588 break; // handle below as a normal binary operation
1589 // otherwise, we need to do dynamic short circuiting on the right operand
1590 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1591 builder.clearAccessChain();
1592 builder.setAccessChainRValue(result);
1593 }
1594 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001595 default:
1596 break;
1597 }
1598
1599 // Assume generic binary op...
1600
John Kessenich32cfd492016-02-02 12:37:46 -07001601 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.clearAccessChain();
1603 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001604 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001605
John Kessenich32cfd492016-02-02 12:37:46 -07001606 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.clearAccessChain();
1608 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001609 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001610
John Kessenich32cfd492016-02-02 12:37:46 -07001611 // get result
John Kessenichead86222018-03-28 18:01:20 -06001612 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001613 TranslateNoContractionDecoration(node->getType().getQualifier()),
1614 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001615 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001616 convertGlslangToSpvType(node->getType()), left, right,
1617 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001618
John Kessenich50e57562015-12-21 21:21:11 -07001619 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001620 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001621 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001622 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001623 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001624 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001625 return false;
1626 }
John Kessenich140f3df2015-06-26 16:58:36 -06001627}
1628
1629bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1630{
John Kesseniche485c7a2017-05-31 18:50:53 -06001631 builder.setLine(node->getLoc().line);
1632
qining40887662016-04-03 22:20:42 -04001633 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1634 if (node->getType().getQualifier().isSpecConstant())
1635 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1636
John Kessenichfc51d282015-08-19 13:34:18 -06001637 spv::Id result = spv::NoResult;
1638
1639 // try texturing first
1640 result = createImageTextureFunctionCall(node);
1641 if (result != spv::NoResult) {
1642 builder.clearAccessChain();
1643 builder.setAccessChainRValue(result);
1644
1645 return false; // done with this node
1646 }
1647
1648 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001649
1650 if (node->getOp() == glslang::EOpArrayLength) {
1651 // Quite special; won't want to evaluate the operand.
1652
John Kessenich5611c6d2018-04-05 11:25:02 -06001653 // Currently, the front-end does not allow .length() on an array until it is sized,
1654 // except for the last block membeor of an SSBO.
1655 // TODO: If this changes, link-time sized arrays might show up here, and need their
1656 // size extracted.
1657
John Kessenichc9a80832015-09-12 12:17:44 -06001658 // Normal .length() would have been constant folded by the front-end.
1659 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001660 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001661
John Kessenichc9a80832015-09-12 12:17:44 -06001662 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1663 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001664 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1665 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001666
1667 builder.clearAccessChain();
1668 builder.setAccessChainRValue(length);
1669
1670 return false;
1671 }
1672
John Kessenichfc51d282015-08-19 13:34:18 -06001673 // Start by evaluating the operand
1674
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 // Does it need a swizzle inversion? If so, evaluation is inverted;
1676 // operate first on the swizzle base, then apply the swizzle.
1677 spv::Id invertedType = spv::NoType;
1678 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1679 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1680 invertedType = getInvertedSwizzleType(*node->getOperand());
1681
John Kessenich140f3df2015-06-26 16:58:36 -06001682 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001683 if (invertedType != spv::NoType)
1684 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1685 else
1686 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001687
Rex Xufc618912015-09-09 16:42:49 +08001688 spv::Id operand = spv::NoResult;
1689
1690 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1691 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001692 node->getOp() == glslang::EOpAtomicCounter ||
1693 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001694 operand = builder.accessChainGetLValue(); // Special case l-value operands
1695 else
John Kessenich32cfd492016-02-02 12:37:46 -07001696 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001697
John Kessenichead86222018-03-28 18:01:20 -06001698 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001699 TranslateNoContractionDecoration(node->getType().getQualifier()),
1700 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001701
1702 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001703 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001704 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // if not, then possibly an operation
1707 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001708 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001709
1710 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001711 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001712 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001713 builder.addDecoration(result, decorations.nonUniform);
1714 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001715
John Kessenich140f3df2015-06-26 16:58:36 -06001716 builder.clearAccessChain();
1717 builder.setAccessChainRValue(result);
1718
1719 return false; // done with this node
1720 }
1721
1722 // it must be a special case, check...
1723 switch (node->getOp()) {
1724 case glslang::EOpPostIncrement:
1725 case glslang::EOpPostDecrement:
1726 case glslang::EOpPreIncrement:
1727 case glslang::EOpPreDecrement:
1728 {
1729 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001730 spv::Id one = 0;
1731 if (node->getBasicType() == glslang::EbtFloat)
1732 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001733 else if (node->getBasicType() == glslang::EbtDouble)
1734 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001735 else if (node->getBasicType() == glslang::EbtFloat16)
1736 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001737 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1738 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001739 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1740 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001741 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1742 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001743 else
1744 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001745 glslang::TOperator op;
1746 if (node->getOp() == glslang::EOpPreIncrement ||
1747 node->getOp() == glslang::EOpPostIncrement)
1748 op = glslang::EOpAdd;
1749 else
1750 op = glslang::EOpSub;
1751
John Kessenichead86222018-03-28 18:01:20 -06001752 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001753 convertGlslangToSpvType(node->getType()), operand, one,
1754 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001755 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001756
1757 // The result of operation is always stored, but conditionally the
1758 // consumed result. The consumed result is always an r-value.
1759 builder.accessChainStore(result);
1760 builder.clearAccessChain();
1761 if (node->getOp() == glslang::EOpPreIncrement ||
1762 node->getOp() == glslang::EOpPreDecrement)
1763 builder.setAccessChainRValue(result);
1764 else
1765 builder.setAccessChainRValue(operand);
1766 }
1767
1768 return false;
1769
1770 case glslang::EOpEmitStreamVertex:
1771 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1772 return false;
1773 case glslang::EOpEndStreamPrimitive:
1774 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1775 return false;
1776
1777 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001778 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001779 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001780 }
John Kessenich140f3df2015-06-26 16:58:36 -06001781}
1782
1783bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1784{
qining27e04a02016-04-14 16:40:20 -04001785 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1786 if (node->getType().getQualifier().isSpecConstant())
1787 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1788
John Kessenichfc51d282015-08-19 13:34:18 -06001789 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001790 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1791 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001792
1793 // try texturing
1794 result = createImageTextureFunctionCall(node);
1795 if (result != spv::NoResult) {
1796 builder.clearAccessChain();
1797 builder.setAccessChainRValue(result);
1798
1799 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001800 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001801#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001802 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001803#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001804 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001805 // "imageStore" is a special case, which has no result
1806 return false;
1807 }
John Kessenichfc51d282015-08-19 13:34:18 -06001808
John Kessenich140f3df2015-06-26 16:58:36 -06001809 glslang::TOperator binOp = glslang::EOpNull;
1810 bool reduceComparison = true;
1811 bool isMatrix = false;
1812 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001813 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001814
1815 assert(node->getOp());
1816
John Kessenichf6640762016-08-01 19:44:00 -06001817 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001818
1819 switch (node->getOp()) {
1820 case glslang::EOpSequence:
1821 {
1822 if (preVisit)
1823 ++sequenceDepth;
1824 else
1825 --sequenceDepth;
1826
1827 if (sequenceDepth == 1) {
1828 // If this is the parent node of all the functions, we want to see them
1829 // early, so all call points have actual SPIR-V functions to reference.
1830 // In all cases, still let the traverser visit the children for us.
1831 makeFunctions(node->getAsAggregate()->getSequence());
1832
John Kessenich6fccb3c2016-09-19 16:01:41 -06001833 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // anything else gets there, so visit out of order, doing them all now.
1835 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1836
John Kessenich6a60c2f2016-12-08 21:01:59 -07001837 // 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 -06001838 // so do them manually.
1839 visitFunctions(node->getAsAggregate()->getSequence());
1840
1841 return false;
1842 }
1843
1844 return true;
1845 }
1846 case glslang::EOpLinkerObjects:
1847 {
1848 if (visit == glslang::EvPreVisit)
1849 linkageOnly = true;
1850 else
1851 linkageOnly = false;
1852
1853 return true;
1854 }
1855 case glslang::EOpComma:
1856 {
1857 // processing from left to right naturally leaves the right-most
1858 // lying around in the access chain
1859 glslang::TIntermSequence& glslangOperands = node->getSequence();
1860 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1861 glslangOperands[i]->traverse(this);
1862
1863 return false;
1864 }
1865 case glslang::EOpFunction:
1866 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001867 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001868 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001869 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001870 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001871 } else {
1872 handleFunctionEntry(node);
1873 }
1874 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001875 if (inEntryPoint)
1876 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001877 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001878 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001879 }
1880
1881 return true;
1882 case glslang::EOpParameters:
1883 // Parameters will have been consumed by EOpFunction processing, but not
1884 // the body, so we still visited the function node's children, making this
1885 // child redundant.
1886 return false;
1887 case glslang::EOpFunctionCall:
1888 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001889 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001890 if (node->isUserDefined())
1891 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001892 // 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 -07001893 if (result) {
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(result);
1896 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001897 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001898
1899 return false;
1900 }
1901 case glslang::EOpConstructMat2x2:
1902 case glslang::EOpConstructMat2x3:
1903 case glslang::EOpConstructMat2x4:
1904 case glslang::EOpConstructMat3x2:
1905 case glslang::EOpConstructMat3x3:
1906 case glslang::EOpConstructMat3x4:
1907 case glslang::EOpConstructMat4x2:
1908 case glslang::EOpConstructMat4x3:
1909 case glslang::EOpConstructMat4x4:
1910 case glslang::EOpConstructDMat2x2:
1911 case glslang::EOpConstructDMat2x3:
1912 case glslang::EOpConstructDMat2x4:
1913 case glslang::EOpConstructDMat3x2:
1914 case glslang::EOpConstructDMat3x3:
1915 case glslang::EOpConstructDMat3x4:
1916 case glslang::EOpConstructDMat4x2:
1917 case glslang::EOpConstructDMat4x3:
1918 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001919 case glslang::EOpConstructIMat2x2:
1920 case glslang::EOpConstructIMat2x3:
1921 case glslang::EOpConstructIMat2x4:
1922 case glslang::EOpConstructIMat3x2:
1923 case glslang::EOpConstructIMat3x3:
1924 case glslang::EOpConstructIMat3x4:
1925 case glslang::EOpConstructIMat4x2:
1926 case glslang::EOpConstructIMat4x3:
1927 case glslang::EOpConstructIMat4x4:
1928 case glslang::EOpConstructUMat2x2:
1929 case glslang::EOpConstructUMat2x3:
1930 case glslang::EOpConstructUMat2x4:
1931 case glslang::EOpConstructUMat3x2:
1932 case glslang::EOpConstructUMat3x3:
1933 case glslang::EOpConstructUMat3x4:
1934 case glslang::EOpConstructUMat4x2:
1935 case glslang::EOpConstructUMat4x3:
1936 case glslang::EOpConstructUMat4x4:
1937 case glslang::EOpConstructBMat2x2:
1938 case glslang::EOpConstructBMat2x3:
1939 case glslang::EOpConstructBMat2x4:
1940 case glslang::EOpConstructBMat3x2:
1941 case glslang::EOpConstructBMat3x3:
1942 case glslang::EOpConstructBMat3x4:
1943 case glslang::EOpConstructBMat4x2:
1944 case glslang::EOpConstructBMat4x3:
1945 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001946 case glslang::EOpConstructF16Mat2x2:
1947 case glslang::EOpConstructF16Mat2x3:
1948 case glslang::EOpConstructF16Mat2x4:
1949 case glslang::EOpConstructF16Mat3x2:
1950 case glslang::EOpConstructF16Mat3x3:
1951 case glslang::EOpConstructF16Mat3x4:
1952 case glslang::EOpConstructF16Mat4x2:
1953 case glslang::EOpConstructF16Mat4x3:
1954 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001955 isMatrix = true;
1956 // fall through
1957 case glslang::EOpConstructFloat:
1958 case glslang::EOpConstructVec2:
1959 case glslang::EOpConstructVec3:
1960 case glslang::EOpConstructVec4:
1961 case glslang::EOpConstructDouble:
1962 case glslang::EOpConstructDVec2:
1963 case glslang::EOpConstructDVec3:
1964 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001965 case glslang::EOpConstructFloat16:
1966 case glslang::EOpConstructF16Vec2:
1967 case glslang::EOpConstructF16Vec3:
1968 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001969 case glslang::EOpConstructBool:
1970 case glslang::EOpConstructBVec2:
1971 case glslang::EOpConstructBVec3:
1972 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001973 case glslang::EOpConstructInt8:
1974 case glslang::EOpConstructI8Vec2:
1975 case glslang::EOpConstructI8Vec3:
1976 case glslang::EOpConstructI8Vec4:
1977 case glslang::EOpConstructUint8:
1978 case glslang::EOpConstructU8Vec2:
1979 case glslang::EOpConstructU8Vec3:
1980 case glslang::EOpConstructU8Vec4:
1981 case glslang::EOpConstructInt16:
1982 case glslang::EOpConstructI16Vec2:
1983 case glslang::EOpConstructI16Vec3:
1984 case glslang::EOpConstructI16Vec4:
1985 case glslang::EOpConstructUint16:
1986 case glslang::EOpConstructU16Vec2:
1987 case glslang::EOpConstructU16Vec3:
1988 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001989 case glslang::EOpConstructInt:
1990 case glslang::EOpConstructIVec2:
1991 case glslang::EOpConstructIVec3:
1992 case glslang::EOpConstructIVec4:
1993 case glslang::EOpConstructUint:
1994 case glslang::EOpConstructUVec2:
1995 case glslang::EOpConstructUVec3:
1996 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001997 case glslang::EOpConstructInt64:
1998 case glslang::EOpConstructI64Vec2:
1999 case glslang::EOpConstructI64Vec3:
2000 case glslang::EOpConstructI64Vec4:
2001 case glslang::EOpConstructUint64:
2002 case glslang::EOpConstructU64Vec2:
2003 case glslang::EOpConstructU64Vec3:
2004 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002005 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002006 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002007 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002008 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002010 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002011 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002012 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002013 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002014 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002015 std::vector<spv::Id> constituents;
2016 for (int c = 0; c < (int)arguments.size(); ++c)
2017 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002018 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002019 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002020 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002021 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002022 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002023
2024 builder.clearAccessChain();
2025 builder.setAccessChainRValue(constructed);
2026
2027 return false;
2028 }
2029
2030 // These six are component-wise compares with component-wise results.
2031 // Forward on to createBinaryOperation(), requesting a vector result.
2032 case glslang::EOpLessThan:
2033 case glslang::EOpGreaterThan:
2034 case glslang::EOpLessThanEqual:
2035 case glslang::EOpGreaterThanEqual:
2036 case glslang::EOpVectorEqual:
2037 case glslang::EOpVectorNotEqual:
2038 {
2039 // Map the operation to a binary
2040 binOp = node->getOp();
2041 reduceComparison = false;
2042 switch (node->getOp()) {
2043 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2044 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2045 default: binOp = node->getOp(); break;
2046 }
2047
2048 break;
2049 }
2050 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002051 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002052 binOp = glslang::EOpMul;
2053 break;
2054 case glslang::EOpOuterProduct:
2055 // two vectors multiplied to make a matrix
2056 binOp = glslang::EOpOuterProduct;
2057 break;
2058 case glslang::EOpDot:
2059 {
qining25262b32016-05-06 17:25:16 -04002060 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002061 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002062 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002063 binOp = glslang::EOpMul;
2064 break;
2065 }
2066 case glslang::EOpMod:
2067 // when an aggregate, this is the floating-point mod built-in function,
2068 // which can be emitted by the one in createBinaryOperation()
2069 binOp = glslang::EOpMod;
2070 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002071 case glslang::EOpEmitVertex:
2072 case glslang::EOpEndPrimitive:
2073 case glslang::EOpBarrier:
2074 case glslang::EOpMemoryBarrier:
2075 case glslang::EOpMemoryBarrierAtomicCounter:
2076 case glslang::EOpMemoryBarrierBuffer:
2077 case glslang::EOpMemoryBarrierImage:
2078 case glslang::EOpMemoryBarrierShared:
2079 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002080 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002081 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002082 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002083 case glslang::EOpWorkgroupMemoryBarrier:
2084 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002085 case glslang::EOpSubgroupBarrier:
2086 case glslang::EOpSubgroupMemoryBarrier:
2087 case glslang::EOpSubgroupMemoryBarrierBuffer:
2088 case glslang::EOpSubgroupMemoryBarrierImage:
2089 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002090 noReturnValue = true;
2091 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2092 break;
2093
Jeff Bolz36831c92018-09-05 10:11:41 -05002094 case glslang::EOpAtomicStore:
2095 noReturnValue = true;
2096 // fallthrough
2097 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002098 case glslang::EOpAtomicAdd:
2099 case glslang::EOpAtomicMin:
2100 case glslang::EOpAtomicMax:
2101 case glslang::EOpAtomicAnd:
2102 case glslang::EOpAtomicOr:
2103 case glslang::EOpAtomicXor:
2104 case glslang::EOpAtomicExchange:
2105 case glslang::EOpAtomicCompSwap:
2106 atomic = true;
2107 break;
2108
John Kessenich0d0c6d32017-07-23 16:08:26 -06002109 case glslang::EOpAtomicCounterAdd:
2110 case glslang::EOpAtomicCounterSubtract:
2111 case glslang::EOpAtomicCounterMin:
2112 case glslang::EOpAtomicCounterMax:
2113 case glslang::EOpAtomicCounterAnd:
2114 case glslang::EOpAtomicCounterOr:
2115 case glslang::EOpAtomicCounterXor:
2116 case glslang::EOpAtomicCounterExchange:
2117 case glslang::EOpAtomicCounterCompSwap:
2118 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2119 builder.addCapability(spv::CapabilityAtomicStorageOps);
2120 atomic = true;
2121 break;
2122
John Kessenich140f3df2015-06-26 16:58:36 -06002123 default:
2124 break;
2125 }
2126
2127 //
2128 // See if it maps to a regular operation.
2129 //
John Kessenich140f3df2015-06-26 16:58:36 -06002130 if (binOp != glslang::EOpNull) {
2131 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2132 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2133 assert(left && right);
2134
2135 builder.clearAccessChain();
2136 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002137 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002138
2139 builder.clearAccessChain();
2140 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002141 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002142
John Kesseniche485c7a2017-05-31 18:50:53 -06002143 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002144 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002145 TranslateNoContractionDecoration(node->getType().getQualifier()),
2146 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002147 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002148 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002149 left->getType().getBasicType(), reduceComparison);
2150
2151 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002152 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002153 builder.clearAccessChain();
2154 builder.setAccessChainRValue(result);
2155
2156 return false;
2157 }
2158
John Kessenich426394d2015-07-23 10:22:48 -06002159 //
2160 // Create the list of operands.
2161 //
John Kessenich140f3df2015-06-26 16:58:36 -06002162 glslang::TIntermSequence& glslangOperands = node->getSequence();
2163 std::vector<spv::Id> operands;
2164 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002165 // special case l-value operands; there are just a few
2166 bool lvalue = false;
2167 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002168 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002169 case glslang::EOpModf:
2170 if (arg == 1)
2171 lvalue = true;
2172 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002173 case glslang::EOpInterpolateAtSample:
2174 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002175#ifdef AMD_EXTENSIONS
2176 case glslang::EOpInterpolateAtVertex:
2177#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002178 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002179 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002180
2181 // Does it need a swizzle inversion? If so, evaluation is inverted;
2182 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002183 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002184 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2185 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2186 }
Rex Xu7a26c172015-12-08 17:12:09 +08002187 break;
Rex Xud4782c12015-09-06 16:30:11 +08002188 case glslang::EOpAtomicAdd:
2189 case glslang::EOpAtomicMin:
2190 case glslang::EOpAtomicMax:
2191 case glslang::EOpAtomicAnd:
2192 case glslang::EOpAtomicOr:
2193 case glslang::EOpAtomicXor:
2194 case glslang::EOpAtomicExchange:
2195 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002196 case glslang::EOpAtomicLoad:
2197 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002198 case glslang::EOpAtomicCounterAdd:
2199 case glslang::EOpAtomicCounterSubtract:
2200 case glslang::EOpAtomicCounterMin:
2201 case glslang::EOpAtomicCounterMax:
2202 case glslang::EOpAtomicCounterAnd:
2203 case glslang::EOpAtomicCounterOr:
2204 case glslang::EOpAtomicCounterXor:
2205 case glslang::EOpAtomicCounterExchange:
2206 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002207 if (arg == 0)
2208 lvalue = true;
2209 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002210 case glslang::EOpAddCarry:
2211 case glslang::EOpSubBorrow:
2212 if (arg == 2)
2213 lvalue = true;
2214 break;
2215 case glslang::EOpUMulExtended:
2216 case glslang::EOpIMulExtended:
2217 if (arg >= 2)
2218 lvalue = true;
2219 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002220 default:
2221 break;
2222 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002223 builder.clearAccessChain();
2224 if (invertedType != spv::NoType && arg == 0)
2225 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2226 else
2227 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002228 if (lvalue)
2229 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002230 else {
2231 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002232 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002233 }
John Kessenich140f3df2015-06-26 16:58:36 -06002234 }
John Kessenich426394d2015-07-23 10:22:48 -06002235
John Kesseniche485c7a2017-05-31 18:50:53 -06002236 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002237 if (atomic) {
2238 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002239 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002240 } else {
2241 // Pass through to generic operations.
2242 switch (glslangOperands.size()) {
2243 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002244 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002245 break;
2246 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002247 {
2248 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002249 TranslateNoContractionDecoration(node->getType().getQualifier()),
2250 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002251 result = createUnaryOperation(
2252 node->getOp(), decorations,
2253 resultType(), operands.front(),
2254 glslangOperands[0]->getAsTyped()->getBasicType());
2255 }
John Kessenich426394d2015-07-23 10:22:48 -06002256 break;
2257 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002259 break;
2260 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002261 if (invertedType)
2262 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002263 }
2264
2265 if (noReturnValue)
2266 return false;
2267
2268 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002269 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002270 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002271 } else {
2272 builder.clearAccessChain();
2273 builder.setAccessChainRValue(result);
2274 return false;
2275 }
2276}
2277
John Kessenich433e9ff2017-01-26 20:31:11 -07002278// This path handles both if-then-else and ?:
2279// The if-then-else has a node type of void, while
2280// ?: has either a void or a non-void node type
2281//
2282// Leaving the result, when not void:
2283// GLSL only has r-values as the result of a :?, but
2284// if we have an l-value, that can be more efficient if it will
2285// become the base of a complex r-value expression, because the
2286// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002287bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2288{
John Kessenich4bee5312018-02-20 21:29:05 -07002289 // See if it simple and safe, or required, to execute both sides.
2290 // Crucially, side effects must be either semantically required or avoided,
2291 // and there are performance trade-offs.
2292 // Return true if required or a good idea (and safe) to execute both sides,
2293 // false otherwise.
2294 const auto bothSidesPolicy = [&]() -> bool {
2295 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002296 if (node->getTrueBlock() == nullptr ||
2297 node->getFalseBlock() == nullptr)
2298 return false;
2299
John Kessenich4bee5312018-02-20 21:29:05 -07002300 // required? (unless we write additional code to look for side effects
2301 // and make performance trade-offs if none are present)
2302 if (!node->getShortCircuit())
2303 return true;
2304
2305 // if not required to execute both, decide based on performance/practicality...
2306
2307 // see if OpSelect can handle it
2308 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2309 node->getBasicType() == glslang::EbtVoid)
2310 return false;
2311
John Kessenich433e9ff2017-01-26 20:31:11 -07002312 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2313 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2314
2315 // return true if a single operand to ? : is okay for OpSelect
2316 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002317 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002318 };
2319
2320 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2321 operandOkay(node->getFalseBlock()->getAsTyped());
2322 };
2323
John Kessenich4bee5312018-02-20 21:29:05 -07002324 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2325 // emit the condition before doing anything with selection
2326 node->getCondition()->traverse(this);
2327 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2328
2329 // Find a way of executing both sides and selecting the right result.
2330 const auto executeBothSides = [&]() -> void {
2331 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002332 node->getTrueBlock()->traverse(this);
2333 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2334 node->getFalseBlock()->traverse(this);
2335 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2336
John Kesseniche485c7a2017-05-31 18:50:53 -06002337 builder.setLine(node->getLoc().line);
2338
John Kessenich4bee5312018-02-20 21:29:05 -07002339 // done if void
2340 if (node->getBasicType() == glslang::EbtVoid)
2341 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002342
John Kessenich4bee5312018-02-20 21:29:05 -07002343 // emit code to select between trueValue and falseValue
2344
2345 // see if OpSelect can handle it
2346 if (node->getType().isScalar() || node->getType().isVector()) {
2347 // Emit OpSelect for this selection.
2348
2349 // smear condition to vector, if necessary (AST is always scalar)
2350 if (builder.isVector(trueValue))
2351 condition = builder.smearScalar(spv::NoPrecision, condition,
2352 builder.makeVectorType(builder.makeBoolType(),
2353 builder.getNumComponents(trueValue)));
2354
2355 // OpSelect
2356 result = builder.createTriOp(spv::OpSelect,
2357 convertGlslangToSpvType(node->getType()), condition,
2358 trueValue, falseValue);
2359
2360 builder.clearAccessChain();
2361 builder.setAccessChainRValue(result);
2362 } else {
2363 // We need control flow to select the result.
2364 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2365 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2366
2367 // Selection control:
2368 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2369
2370 // make an "if" based on the value created by the condition
2371 spv::Builder::If ifBuilder(condition, control, builder);
2372
2373 // emit the "then" statement
2374 builder.createStore(trueValue, result);
2375 ifBuilder.makeBeginElse();
2376 // emit the "else" statement
2377 builder.createStore(falseValue, result);
2378
2379 // finish off the control flow
2380 ifBuilder.makeEndIf();
2381
2382 builder.clearAccessChain();
2383 builder.setAccessChainLValue(result);
2384 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002385 };
2386
John Kessenich4bee5312018-02-20 21:29:05 -07002387 // Execute the one side needed, as per the condition
2388 const auto executeOneSide = [&]() {
2389 // Always emit control flow.
2390 if (node->getBasicType() != glslang::EbtVoid)
2391 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002392
John Kessenich4bee5312018-02-20 21:29:05 -07002393 // Selection control:
2394 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2395
2396 // make an "if" based on the value created by the condition
2397 spv::Builder::If ifBuilder(condition, control, builder);
2398
2399 // emit the "then" statement
2400 if (node->getTrueBlock() != nullptr) {
2401 node->getTrueBlock()->traverse(this);
2402 if (result != spv::NoResult)
2403 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2404 }
2405
2406 if (node->getFalseBlock() != nullptr) {
2407 ifBuilder.makeBeginElse();
2408 // emit the "else" statement
2409 node->getFalseBlock()->traverse(this);
2410 if (result != spv::NoResult)
2411 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2412 }
2413
2414 // finish off the control flow
2415 ifBuilder.makeEndIf();
2416
2417 if (result != spv::NoResult) {
2418 builder.clearAccessChain();
2419 builder.setAccessChainLValue(result);
2420 }
2421 };
2422
2423 // Try for OpSelect (or a requirement to execute both sides)
2424 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002425 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2426 if (node->getType().getQualifier().isSpecConstant())
2427 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002428 executeBothSides();
2429 } else
2430 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002431
2432 return false;
2433}
2434
2435bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2436{
2437 // emit and get the condition before doing anything with switch
2438 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002439 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002440
Rex Xu57e65922017-07-04 23:23:40 +08002441 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002442 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002443
John Kessenich140f3df2015-06-26 16:58:36 -06002444 // browse the children to sort out code segments
2445 int defaultSegment = -1;
2446 std::vector<TIntermNode*> codeSegments;
2447 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2448 std::vector<int> caseValues;
2449 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2450 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2451 TIntermNode* child = *c;
2452 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002453 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002454 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002455 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002456 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2457 } else
2458 codeSegments.push_back(child);
2459 }
2460
qining25262b32016-05-06 17:25:16 -04002461 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002462 // statements between the last case and the end of the switch statement
2463 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2464 (int)codeSegments.size() == defaultSegment)
2465 codeSegments.push_back(nullptr);
2466
2467 // make the switch statement
2468 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002469 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002470
2471 // emit all the code in the segments
2472 breakForLoop.push(false);
2473 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2474 builder.nextSwitchSegment(segmentBlocks, s);
2475 if (codeSegments[s])
2476 codeSegments[s]->traverse(this);
2477 else
2478 builder.addSwitchBreak();
2479 }
2480 breakForLoop.pop();
2481
2482 builder.endSwitch(segmentBlocks);
2483
2484 return false;
2485}
2486
2487void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2488{
2489 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002490 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002491
2492 builder.clearAccessChain();
2493 builder.setAccessChainRValue(constant);
2494}
2495
2496bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2497{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002498 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002499 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002500
2501 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002502 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2503 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002504
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002505 // Spec requires back edges to target header blocks, and every header block
2506 // must dominate its merge block. Make a header block first to ensure these
2507 // conditions are met. By definition, it will contain OpLoopMerge, followed
2508 // by a block-ending branch. But we don't want to put any other body/test
2509 // instructions in it, since the body/test may have arbitrary instructions,
2510 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002511 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002512 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002513 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002514 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002515 spv::Block& test = builder.makeNewBlock();
2516 builder.createBranch(&test);
2517
2518 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002519 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002520 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002521 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2522
2523 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002524 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002525 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002526 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002527 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002528 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002529
2530 builder.setBuildPoint(&blocks.continue_target);
2531 if (node->getTerminal())
2532 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002533 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002534 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002535 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002536 builder.createBranch(&blocks.body);
2537
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002538 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002539 builder.setBuildPoint(&blocks.body);
2540 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002541 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002542 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002543 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002544
2545 builder.setBuildPoint(&blocks.continue_target);
2546 if (node->getTerminal())
2547 node->getTerminal()->traverse(this);
2548 if (node->getTest()) {
2549 node->getTest()->traverse(this);
2550 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002551 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002552 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002553 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002554 // TODO: unless there was a break/return/discard instruction
2555 // somewhere in the body, this is an infinite loop, so we should
2556 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002557 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002558 }
John Kessenich140f3df2015-06-26 16:58:36 -06002559 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002560 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002561 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002562 return false;
2563}
2564
2565bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2566{
2567 if (node->getExpression())
2568 node->getExpression()->traverse(this);
2569
John Kesseniche485c7a2017-05-31 18:50:53 -06002570 builder.setLine(node->getLoc().line);
2571
John Kessenich140f3df2015-06-26 16:58:36 -06002572 switch (node->getFlowOp()) {
2573 case glslang::EOpKill:
2574 builder.makeDiscard();
2575 break;
2576 case glslang::EOpBreak:
2577 if (breakForLoop.top())
2578 builder.createLoopExit();
2579 else
2580 builder.addSwitchBreak();
2581 break;
2582 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002583 builder.createLoopContinue();
2584 break;
2585 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002586 if (node->getExpression()) {
2587 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2588 spv::Id returnId = accessChainLoad(glslangReturnType);
2589 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2590 builder.clearAccessChain();
2591 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2592 builder.setAccessChainLValue(copyId);
2593 multiTypeStore(glslangReturnType, returnId);
2594 returnId = builder.createLoad(copyId);
2595 }
2596 builder.makeReturn(false, returnId);
2597 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002598 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002599
2600 builder.clearAccessChain();
2601 break;
2602
2603 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002604 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002605 break;
2606 }
2607
2608 return false;
2609}
2610
2611spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2612{
qining25262b32016-05-06 17:25:16 -04002613 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002614 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002615 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002616 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002617 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002618 }
2619
2620 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002621 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002622 spv::Id spvType = convertGlslangToSpvType(node->getType());
2623
Rex Xucabbb782017-03-24 13:41:14 +08002624 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2625 node->getType().containsBasicType(glslang::EbtInt16) ||
2626 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002627 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002628 switch (storageClass) {
2629 case spv::StorageClassInput:
2630 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002631 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002632 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002633 break;
2634 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002635 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002636 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002637 break;
2638 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002639 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002640 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2641 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002642 else
2643 builder.addCapability(spv::CapabilityStorageUniform16);
2644 break;
2645 case spv::StorageClassStorageBuffer:
2646 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2647 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2648 break;
2649 default:
2650 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002651 }
2652 }
Rex Xuf89ad982017-04-07 23:22:33 +08002653
John Kessenich312dcfb2018-07-03 13:19:51 -06002654 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2655 node->getType().containsBasicType(glslang::EbtUint8);
2656 if (contains8BitType) {
2657 if (storageClass == spv::StorageClassPushConstant) {
2658 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2659 builder.addCapability(spv::CapabilityStoragePushConstant8);
2660 } else if (storageClass == spv::StorageClassUniform) {
2661 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2662 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2663 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2664 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2665 }
2666 }
2667
John Kessenich140f3df2015-06-26 16:58:36 -06002668 const char* name = node->getName().c_str();
2669 if (glslang::IsAnonymous(name))
2670 name = "";
2671
2672 return builder.createVariable(storageClass, spvType, name);
2673}
2674
2675// Return type Id of the sampled type.
2676spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2677{
2678 switch (sampler.type) {
2679 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002680#ifdef AMD_EXTENSIONS
2681 case glslang::EbtFloat16:
2682 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2683 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2684 return builder.makeFloatType(16);
2685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002686 case glslang::EbtInt: return builder.makeIntType(32);
2687 case glslang::EbtUint: return builder.makeUintType(32);
2688 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002689 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 return builder.makeFloatType(32);
2691 }
2692}
2693
John Kessenich8c8505c2016-07-26 12:50:38 -06002694// If node is a swizzle operation, return the type that should be used if
2695// the swizzle base is first consumed by another operation, before the swizzle
2696// is applied.
2697spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2698{
John Kessenichecba76f2017-01-06 00:34:48 -07002699 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002700 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2701 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2702 else
2703 return spv::NoType;
2704}
2705
2706// When inverting a swizzle with a parent op, this function
2707// will apply the swizzle operation to a completed parent operation.
2708spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2709{
2710 std::vector<unsigned> swizzle;
2711 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2712 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2713}
2714
John Kessenich8c8505c2016-07-26 12:50:38 -06002715// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2716void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2717{
2718 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2719 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2720 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2721}
2722
John Kessenich3ac051e2015-12-20 11:29:16 -07002723// Convert from a glslang type to an SPV type, by calling into a
2724// recursive version of this function. This establishes the inherited
2725// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002726spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2727{
John Kessenichead86222018-03-28 18:01:20 -06002728 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002729}
2730
2731// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002732// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002733// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002734spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2735 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002736{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002737 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002738
2739 switch (type.getBasicType()) {
2740 case glslang::EbtVoid:
2741 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002742 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EbtFloat:
2745 spvType = builder.makeFloatType(32);
2746 break;
2747 case glslang::EbtDouble:
2748 spvType = builder.makeFloatType(64);
2749 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002750 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002751 spvType = builder.makeFloatType(16);
2752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002753 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002754 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2755 // a 32-bit int where non-0 means true.
2756 if (explicitLayout != glslang::ElpNone)
2757 spvType = builder.makeUintType(32);
2758 else
2759 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002761 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002762 spvType = builder.makeIntType(8);
2763 break;
2764 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002765 spvType = builder.makeUintType(8);
2766 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002767 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002768 spvType = builder.makeIntType(16);
2769 break;
2770 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002771 spvType = builder.makeUintType(16);
2772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002773 case glslang::EbtInt:
2774 spvType = builder.makeIntType(32);
2775 break;
2776 case glslang::EbtUint:
2777 spvType = builder.makeUintType(32);
2778 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002779 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002780 spvType = builder.makeIntType(64);
2781 break;
2782 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002783 spvType = builder.makeUintType(64);
2784 break;
John Kessenich426394d2015-07-23 10:22:48 -06002785 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002786 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002787 spvType = builder.makeUintType(32);
2788 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002789 case glslang::EbtSampler:
2790 {
2791 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002792 if (sampler.sampler) {
2793 // pure sampler
2794 spvType = builder.makeSamplerType();
2795 } else {
2796 // an image is present, make its type
2797 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2798 sampler.image ? 2 : 1, TranslateImageFormat(type));
2799 if (sampler.combined) {
2800 // already has both image and sampler, make the combined type
2801 spvType = builder.makeSampledImageType(spvType);
2802 }
John Kessenich55e7d112015-11-15 21:33:39 -07002803 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002804 }
John Kessenich140f3df2015-06-26 16:58:36 -06002805 break;
2806 case glslang::EbtStruct:
2807 case glslang::EbtBlock:
2808 {
2809 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002810 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002811
2812 // Try to share structs for different layouts, but not yet for other
2813 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002814 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002815 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002816 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818
2819 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002820 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002821 memberRemapper[glslangMembers].resize(glslangMembers->size());
2822 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002823 }
2824 break;
2825 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002826 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002827 break;
2828 }
2829
2830 if (type.isMatrix())
2831 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2832 else {
2833 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2834 if (type.getVectorSize() > 1)
2835 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2836 }
2837
2838 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002839 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2840
John Kessenichc9a80832015-09-12 12:17:44 -06002841 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002842 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002843 // We need to decorate array strides for types needing explicit layout, except blocks.
2844 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002845 // Use a dummy glslang type for querying internal strides of
2846 // arrays of arrays, but using just a one-dimensional array.
2847 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002848 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2849 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002850
2851 // Will compute the higher-order strides here, rather than making a whole
2852 // pile of types and doing repetitive recursion on their contents.
2853 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2854 }
John Kessenichf8842e52016-01-04 19:22:56 -07002855
2856 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002857 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002858 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002859 if (stride > 0)
2860 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002861 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002862 }
2863 } else {
2864 // single-dimensional array, and don't yet have stride
2865
John Kessenichf8842e52016-01-04 19:22:56 -07002866 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002867 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2868 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002869 }
John Kessenich31ed4832015-09-09 17:51:38 -06002870
John Kessenichead86222018-03-28 18:01:20 -06002871 // Do the outer dimension, which might not be known for a runtime-sized array.
2872 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2873 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002874 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002875 else {
2876 if (!lastBufferBlockMember) {
2877 builder.addExtension("SPV_EXT_descriptor_indexing");
2878 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2879 }
John Kessenichead86222018-03-28 18:01:20 -06002880 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002881 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002882 if (stride > 0)
2883 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 }
2885
2886 return spvType;
2887}
2888
John Kessenich0e737842017-03-24 18:38:16 -06002889// TODO: this functionality should exist at a higher level, in creating the AST
2890//
2891// Identify interface members that don't have their required extension turned on.
2892//
2893bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2894{
2895 auto& extensions = glslangIntermediate->getRequestedExtensions();
2896
Rex Xubcf291a2017-03-29 23:01:36 +08002897 if (member.getFieldName() == "gl_ViewportMask" &&
2898 extensions.find("GL_NV_viewport_array2") == extensions.end())
2899 return true;
2900 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2901 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2902 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002903 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2904 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2905 return true;
2906 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2907 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2908 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002909 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2910 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2911 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002912
2913 return false;
2914};
2915
John Kessenich6090df02016-06-30 21:18:02 -06002916// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2917// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2918// Mutually recursive with convertGlslangToSpvType().
2919spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2920 const glslang::TTypeList* glslangMembers,
2921 glslang::TLayoutPacking explicitLayout,
2922 const glslang::TQualifier& qualifier)
2923{
2924 // Create a vector of struct types for SPIR-V to consume
2925 std::vector<spv::Id> spvMembers;
2926 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002927 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2928 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2929 if (glslangMember.hiddenMember()) {
2930 ++memberDelta;
2931 if (type.getBasicType() == glslang::EbtBlock)
2932 memberRemapper[glslangMembers][i] = -1;
2933 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002934 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002935 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002936 if (filterMember(glslangMember))
2937 continue;
2938 }
John Kessenich6090df02016-06-30 21:18:02 -06002939 // modify just this child's view of the qualifier
2940 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2941 InheritQualifiers(memberQualifier, qualifier);
2942
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002943 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002944 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002945 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002946
2947 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002948 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2949 i == (int)glslangMembers->size() - 1;
2950 spvMembers.push_back(
2951 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002952 }
2953 }
2954
2955 // Make the SPIR-V type
2956 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002957 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002958 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2959
2960 // Decorate it
2961 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2962
2963 return spvType;
2964}
2965
2966void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2967 const glslang::TTypeList* glslangMembers,
2968 glslang::TLayoutPacking explicitLayout,
2969 const glslang::TQualifier& qualifier,
2970 spv::Id spvType)
2971{
2972 // Name and decorate the non-hidden members
2973 int offset = -1;
2974 int locationOffset = 0; // for use within the members of this struct
2975 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2976 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2977 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002978 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002979 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002980 if (filterMember(glslangMember))
2981 continue;
2982 }
John Kessenich6090df02016-06-30 21:18:02 -06002983
2984 // modify just this child's view of the qualifier
2985 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2986 InheritQualifiers(memberQualifier, qualifier);
2987
2988 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002989 if (member < 0)
2990 continue;
2991
2992 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2993 builder.addMemberDecoration(spvType, member,
2994 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2995 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2996 // Add interpolation and auxiliary storage decorations only to
2997 // top-level members of Input and Output storage classes
2998 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2999 type.getQualifier().storage == glslang::EvqVaryingOut) {
3000 if (type.getBasicType() == glslang::EbtBlock ||
3001 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3002 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3003 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003004 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003005 }
3006 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003007
John Kessenich5d610ee2018-03-07 18:05:55 -07003008 if (type.getBasicType() == glslang::EbtBlock &&
3009 qualifier.storage == glslang::EvqBuffer) {
3010 // Add memory decorations only to top-level members of shader storage block
3011 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003012 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003013 for (unsigned int i = 0; i < memory.size(); ++i)
3014 builder.addMemberDecoration(spvType, member, memory[i]);
3015 }
John Kessenich6090df02016-06-30 21:18:02 -06003016
John Kessenich5d610ee2018-03-07 18:05:55 -07003017 // Location assignment was already completed correctly by the front end,
3018 // just track whether a member needs to be decorated.
3019 // Ignore member locations if the container is an array, as that's
3020 // ill-specified and decisions have been made to not allow this.
3021 if (! type.isArray() && memberQualifier.hasLocation())
3022 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003023
John Kessenich5d610ee2018-03-07 18:05:55 -07003024 if (qualifier.hasLocation()) // track for upcoming inheritance
3025 locationOffset += glslangIntermediate->computeTypeLocationSize(
3026 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003027
John Kessenich5d610ee2018-03-07 18:05:55 -07003028 // component, XFB, others
3029 if (glslangMember.getQualifier().hasComponent())
3030 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3031 glslangMember.getQualifier().layoutComponent);
3032 if (glslangMember.getQualifier().hasXfbOffset())
3033 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3034 glslangMember.getQualifier().layoutXfbOffset);
3035 else if (explicitLayout != glslang::ElpNone) {
3036 // figure out what to do with offset, which is accumulating
3037 int nextOffset;
3038 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3039 if (offset >= 0)
3040 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3041 offset = nextOffset;
3042 }
John Kessenich6090df02016-06-30 21:18:02 -06003043
John Kessenich5d610ee2018-03-07 18:05:55 -07003044 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3045 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3046 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003047
John Kessenich5d610ee2018-03-07 18:05:55 -07003048 // built-in variable decorations
3049 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3050 if (builtIn != spv::BuiltInMax)
3051 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003052
John Kessenich5611c6d2018-04-05 11:25:02 -06003053 // nonuniform
3054 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3055
John Kessenichead86222018-03-28 18:01:20 -06003056 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3057 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3058 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3059 memberQualifier.semanticName);
3060 }
3061
chaoc771d89f2017-01-13 01:10:53 -08003062#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003063 if (builtIn == spv::BuiltInLayer) {
3064 // SPV_NV_viewport_array2 extension
3065 if (glslangMember.getQualifier().layoutViewportRelative){
3066 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3067 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3068 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003069 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003070 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3071 builder.addMemberDecoration(spvType, member,
3072 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3073 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3074 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3075 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003076 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003077 }
3078 if (glslangMember.getQualifier().layoutPassthrough) {
3079 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3080 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3081 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3082 }
chaoc771d89f2017-01-13 01:10:53 -08003083#endif
John Kessenich6090df02016-06-30 21:18:02 -06003084 }
3085
3086 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003087 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3088 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003089 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3090 builder.addCapability(spv::CapabilityGeometryStreams);
3091 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3092 }
John Kessenich6090df02016-06-30 21:18:02 -06003093}
3094
John Kessenich6c292d32016-02-15 20:58:50 -07003095// Turn the expression forming the array size into an id.
3096// This is not quite trivial, because of specialization constants.
3097// Sometimes, a raw constant is turned into an Id, and sometimes
3098// a specialization constant expression is.
3099spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3100{
3101 // First, see if this is sized with a node, meaning a specialization constant:
3102 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3103 if (specNode != nullptr) {
3104 builder.clearAccessChain();
3105 specNode->traverse(this);
3106 return accessChainLoad(specNode->getAsTyped()->getType());
3107 }
qining25262b32016-05-06 17:25:16 -04003108
John Kessenich6c292d32016-02-15 20:58:50 -07003109 // Otherwise, need a compile-time (front end) size, get it:
3110 int size = arraySizes.getDimSize(dim);
3111 assert(size > 0);
3112 return builder.makeUintConstant(size);
3113}
3114
John Kessenich103bef92016-02-08 21:38:15 -07003115// Wrap the builder's accessChainLoad to:
3116// - localize handling of RelaxedPrecision
3117// - use the SPIR-V inferred type instead of another conversion of the glslang type
3118// (avoids unnecessary work and possible type punning for structures)
3119// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003120spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3121{
John Kessenich103bef92016-02-08 21:38:15 -07003122 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003123
3124 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3125 coherentFlags |= TranslateCoherent(type);
3126
John Kessenich5611c6d2018-04-05 11:25:02 -06003127 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003128 TranslateNonUniformDecoration(type.getQualifier()),
3129 nominalTypeId,
3130 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3131 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003132
3133 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003134 if (type.getBasicType() == glslang::EbtBool) {
3135 if (builder.isScalarType(nominalTypeId)) {
3136 // Conversion for bool
3137 spv::Id boolType = builder.makeBoolType();
3138 if (nominalTypeId != boolType)
3139 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3140 } else if (builder.isVectorType(nominalTypeId)) {
3141 // Conversion for bvec
3142 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3143 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3144 if (nominalTypeId != bvecType)
3145 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3146 }
3147 }
John Kessenich103bef92016-02-08 21:38:15 -07003148
3149 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003150}
3151
Rex Xu27253232016-02-23 17:51:09 +08003152// Wrap the builder's accessChainStore to:
3153// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003154//
3155// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003156void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3157{
3158 // Need to convert to abstract types when necessary
3159 if (type.getBasicType() == glslang::EbtBool) {
3160 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3161
3162 if (builder.isScalarType(nominalTypeId)) {
3163 // Conversion for bool
3164 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003165 if (nominalTypeId != boolType) {
3166 // keep these outside arguments, for determinant order-of-evaluation
3167 spv::Id one = builder.makeUintConstant(1);
3168 spv::Id zero = builder.makeUintConstant(0);
3169 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3170 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003171 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003172 } else if (builder.isVectorType(nominalTypeId)) {
3173 // Conversion for bvec
3174 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3175 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003176 if (nominalTypeId != bvecType) {
3177 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003178 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3179 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3180 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003181 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003182 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3183 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003184 }
3185 }
3186
Jeff Bolz36831c92018-09-05 10:11:41 -05003187 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3188 coherentFlags |= TranslateCoherent(type);
3189
3190 builder.accessChainStore(rvalue,
3191 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3192 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003193}
3194
John Kessenich4bf71552016-09-02 11:20:21 -06003195// For storing when types match at the glslang level, but not might match at the
3196// SPIR-V level.
3197//
3198// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003199// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003200// as in a member-decorated way.
3201//
3202// NOTE: This function can handle any store request; if it's not special it
3203// simplifies to a simple OpStore.
3204//
3205// Implicitly uses the existing builder.accessChain as the storage target.
3206void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3207{
John Kessenichb3e24e42016-09-11 12:33:43 -06003208 // we only do the complex path here if it's an aggregate
3209 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003210 accessChainStore(type, rValue);
3211 return;
3212 }
3213
John Kessenichb3e24e42016-09-11 12:33:43 -06003214 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003215 spv::Id rType = builder.getTypeId(rValue);
3216 spv::Id lValue = builder.accessChainGetLValue();
3217 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3218 if (lType == rType) {
3219 accessChainStore(type, rValue);
3220 return;
3221 }
3222
John Kessenichb3e24e42016-09-11 12:33:43 -06003223 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003224 // where the two types were the same type in GLSL. This requires member
3225 // by member copy, recursively.
3226
John Kessenichb3e24e42016-09-11 12:33:43 -06003227 // If an array, copy element by element.
3228 if (type.isArray()) {
3229 glslang::TType glslangElementType(type, 0);
3230 spv::Id elementRType = builder.getContainedTypeId(rType);
3231 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3232 // get the source member
3233 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003234
John Kessenichb3e24e42016-09-11 12:33:43 -06003235 // set up the target storage
3236 builder.clearAccessChain();
3237 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003238 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003239
John Kessenichb3e24e42016-09-11 12:33:43 -06003240 // store the member
3241 multiTypeStore(glslangElementType, elementRValue);
3242 }
3243 } else {
3244 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003245
John Kessenichb3e24e42016-09-11 12:33:43 -06003246 // loop over structure members
3247 const glslang::TTypeList& members = *type.getStruct();
3248 for (int m = 0; m < (int)members.size(); ++m) {
3249 const glslang::TType& glslangMemberType = *members[m].type;
3250
3251 // get the source member
3252 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3253 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3254
3255 // set up the target storage
3256 builder.clearAccessChain();
3257 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003258 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003259
3260 // store the member
3261 multiTypeStore(glslangMemberType, memberRValue);
3262 }
John Kessenich4bf71552016-09-02 11:20:21 -06003263 }
3264}
3265
John Kessenichf85e8062015-12-19 13:57:10 -07003266// Decide whether or not this type should be
3267// decorated with offsets and strides, and if so
3268// whether std140 or std430 rules should be applied.
3269glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003270{
John Kessenichf85e8062015-12-19 13:57:10 -07003271 // has to be a block
3272 if (type.getBasicType() != glslang::EbtBlock)
3273 return glslang::ElpNone;
3274
3275 // has to be a uniform or buffer block
3276 if (type.getQualifier().storage != glslang::EvqUniform &&
3277 type.getQualifier().storage != glslang::EvqBuffer)
3278 return glslang::ElpNone;
3279
3280 // return the layout to use
3281 switch (type.getQualifier().layoutPacking) {
3282 case glslang::ElpStd140:
3283 case glslang::ElpStd430:
3284 return type.getQualifier().layoutPacking;
3285 default:
3286 return glslang::ElpNone;
3287 }
John Kessenich31ed4832015-09-09 17:51:38 -06003288}
3289
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003290// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003291int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003292{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003293 int size;
John Kessenich49987892015-12-29 17:11:44 -07003294 int stride;
3295 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003296
3297 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003298}
3299
John Kessenich49987892015-12-29 17:11:44 -07003300// 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 -07003301// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003302int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003303{
John Kessenich49987892015-12-29 17:11:44 -07003304 glslang::TType elementType;
3305 elementType.shallowCopy(matrixType);
3306 elementType.clearArraySizes();
3307
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003308 int size;
John Kessenich49987892015-12-29 17:11:44 -07003309 int stride;
3310 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3311
3312 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003313}
3314
John Kessenich5e4b1242015-08-06 22:53:06 -06003315// Given a member type of a struct, realign the current offset for it, and compute
3316// the next (not yet aligned) offset for the next member, which will get aligned
3317// on the next call.
3318// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3319// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3320// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003321void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003322 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003323{
3324 // this will get a positive value when deemed necessary
3325 nextOffset = -1;
3326
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 // override anything in currentOffset with user-set offset
3328 if (memberType.getQualifier().hasOffset())
3329 currentOffset = memberType.getQualifier().layoutOffset;
3330
3331 // It could be that current linker usage in glslang updated all the layoutOffset,
3332 // in which case the following code does not matter. But, that's not quite right
3333 // once cross-compilation unit GLSL validation is done, as the original user
3334 // settings are needed in layoutOffset, and then the following will come into play.
3335
John Kessenichf85e8062015-12-19 13:57:10 -07003336 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 if (! memberType.getQualifier().hasOffset())
3338 currentOffset = -1;
3339
3340 return;
3341 }
3342
John Kessenichf85e8062015-12-19 13:57:10 -07003343 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003344 if (currentOffset < 0)
3345 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003346
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3348 // but possibly not yet correctly aligned.
3349
3350 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003351 int dummyStride;
3352 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003353
3354 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003355 // TODO: make this consistent in early phases of code:
3356 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3357 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3358 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003359 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003360 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003361 int dummySize;
3362 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3363 if (componentAlignment <= 4)
3364 memberAlignment = componentAlignment;
3365 }
3366
3367 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003369
3370 // Bump up to vec4 if there is a bad straddle
3371 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3372 glslang::RoundToPow2(currentOffset, 16);
3373
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 nextOffset = currentOffset + memberSize;
3375}
3376
David Netoa901ffe2016-06-08 14:11:40 +01003377void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003378{
David Netoa901ffe2016-06-08 14:11:40 +01003379 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3380 switch (glslangBuiltIn)
3381 {
3382 case glslang::EbvClipDistance:
3383 case glslang::EbvCullDistance:
3384 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003385#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003386 case glslang::EbvViewportMaskNV:
3387 case glslang::EbvSecondaryPositionNV:
3388 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003389 case glslang::EbvPositionPerViewNV:
3390 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003391#endif
David Netoa901ffe2016-06-08 14:11:40 +01003392 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3393 // Alternately, we could just call this for any glslang built-in, since the
3394 // capability already guards against duplicates.
3395 TranslateBuiltInDecoration(glslangBuiltIn, false);
3396 break;
3397 default:
3398 // Capabilities were already generated when the struct was declared.
3399 break;
3400 }
John Kessenichebb50532016-05-16 19:22:05 -06003401}
3402
John Kessenich6fccb3c2016-09-19 16:01:41 -06003403bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003404{
John Kessenicheee9d532016-09-19 18:09:30 -06003405 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003406}
3407
John Kessenichd41993d2017-09-10 15:21:05 -06003408// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003409// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3410// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003411bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003412{
John Kessenich6a14f782017-12-04 02:48:10 -07003413 assert(qualifier == glslang::EvqIn ||
3414 qualifier == glslang::EvqOut ||
3415 qualifier == glslang::EvqInOut ||
3416 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003417 return qualifier != glslang::EvqConstReadOnly;
3418}
3419
3420// Is parameter pass-by-original?
3421bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3422 bool implicitThisParam)
3423{
3424 if (implicitThisParam) // implicit this
3425 return true;
3426 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003427 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003428 return paramType.containsOpaque() || // sampler, etc.
3429 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3430}
3431
John Kessenich140f3df2015-06-26 16:58:36 -06003432// Make all the functions, skeletally, without actually visiting their bodies.
3433void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3434{
Jeff Bolz36831c92018-09-05 10:11:41 -05003435 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003436 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3437 if (paramPrecision != spv::NoPrecision)
3438 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003439 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003440 };
3441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3443 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003444 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003445 continue;
3446
3447 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003448 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003449 //
qining25262b32016-05-06 17:25:16 -04003450 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003451 // function. What it is an address of varies:
3452 //
John Kessenich4bf71552016-09-02 11:20:21 -06003453 // - "in" parameters not marked as "const" can be written to without modifying the calling
3454 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003455 //
3456 // - "const in" parameters can just be the r-value, as no writes need occur.
3457 //
John Kessenich4bf71552016-09-02 11:20:21 -06003458 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3459 // 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 -06003460
3461 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003462 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003463 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3464
John Kessenichfad62972017-07-18 02:35:46 -06003465 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3466 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003467
John Kessenichfad62972017-07-18 02:35:46 -06003468 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003469 for (int p = 0; p < (int)parameters.size(); ++p) {
3470 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3471 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003472 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003473 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003474 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003475 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3476 else
John Kessenich4bf71552016-09-02 11:20:21 -06003477 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003478 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003479 paramTypes.push_back(typeId);
3480 }
3481
3482 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003483 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3484 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003485 glslFunction->getName().c_str(), paramTypes,
3486 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003487 if (implicitThis)
3488 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003489
3490 // Track function to emit/call later
3491 functionMap[glslFunction->getName().c_str()] = function;
3492
3493 // Set the parameter id's
3494 for (int p = 0; p < (int)parameters.size(); ++p) {
3495 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3496 // give a name too
3497 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3498 }
3499 }
3500}
3501
3502// Process all the initializers, while skipping the functions and link objects
3503void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3504{
3505 builder.setBuildPoint(shaderEntry->getLastBlock());
3506 for (int i = 0; i < (int)initializers.size(); ++i) {
3507 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3508 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3509
3510 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003511 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003512 initializer->traverse(this);
3513 }
3514 }
3515}
3516
3517// Process all the functions, while skipping initializers.
3518void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3519{
3520 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3521 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003522 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003523 node->traverse(this);
3524 }
3525}
3526
3527void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3528{
qining25262b32016-05-06 17:25:16 -04003529 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003530 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003531 currentFunction = functionMap[node->getName().c_str()];
3532 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003533 builder.setBuildPoint(functionBlock);
3534}
3535
Rex Xu04db3f52015-09-16 11:44:02 +08003536void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003537{
Rex Xufc618912015-09-09 16:42:49 +08003538 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003539
3540 glslang::TSampler sampler = {};
3541 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003542#ifdef AMD_EXTENSIONS
3543 bool f16ShadowCompare = false;
3544#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003545 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003546 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3547 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003548#ifdef AMD_EXTENSIONS
3549 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3550#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003551 }
3552
John Kessenich140f3df2015-06-26 16:58:36 -06003553 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3554 builder.clearAccessChain();
3555 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003556
3557 // Special case l-value operands
3558 bool lvalue = false;
3559 switch (node.getOp()) {
3560 case glslang::EOpImageAtomicAdd:
3561 case glslang::EOpImageAtomicMin:
3562 case glslang::EOpImageAtomicMax:
3563 case glslang::EOpImageAtomicAnd:
3564 case glslang::EOpImageAtomicOr:
3565 case glslang::EOpImageAtomicXor:
3566 case glslang::EOpImageAtomicExchange:
3567 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003568 case glslang::EOpImageAtomicLoad:
3569 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003570 if (i == 0)
3571 lvalue = true;
3572 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003573 case glslang::EOpSparseImageLoad:
3574 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3575 lvalue = true;
3576 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003577#ifdef AMD_EXTENSIONS
3578 case glslang::EOpSparseTexture:
3579 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3580 lvalue = true;
3581 break;
3582 case glslang::EOpSparseTextureClamp:
3583 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3584 lvalue = true;
3585 break;
3586 case glslang::EOpSparseTextureLod:
3587 case glslang::EOpSparseTextureOffset:
3588 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3589 lvalue = true;
3590 break;
3591#else
Rex Xu48edadf2015-12-31 16:11:41 +08003592 case glslang::EOpSparseTexture:
3593 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3594 lvalue = true;
3595 break;
3596 case glslang::EOpSparseTextureClamp:
3597 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3598 lvalue = true;
3599 break;
3600 case glslang::EOpSparseTextureLod:
3601 case glslang::EOpSparseTextureOffset:
3602 if (i == 3)
3603 lvalue = true;
3604 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003605#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003606 case glslang::EOpSparseTextureFetch:
3607 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3608 lvalue = true;
3609 break;
3610 case glslang::EOpSparseTextureFetchOffset:
3611 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3612 lvalue = true;
3613 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003614#ifdef AMD_EXTENSIONS
3615 case glslang::EOpSparseTextureLodOffset:
3616 case glslang::EOpSparseTextureGrad:
3617 case glslang::EOpSparseTextureOffsetClamp:
3618 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3619 lvalue = true;
3620 break;
3621 case glslang::EOpSparseTextureGradOffset:
3622 case glslang::EOpSparseTextureGradClamp:
3623 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3624 lvalue = true;
3625 break;
3626 case glslang::EOpSparseTextureGradOffsetClamp:
3627 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3628 lvalue = true;
3629 break;
3630#else
Rex Xu48edadf2015-12-31 16:11:41 +08003631 case glslang::EOpSparseTextureLodOffset:
3632 case glslang::EOpSparseTextureGrad:
3633 case glslang::EOpSparseTextureOffsetClamp:
3634 if (i == 4)
3635 lvalue = true;
3636 break;
3637 case glslang::EOpSparseTextureGradOffset:
3638 case glslang::EOpSparseTextureGradClamp:
3639 if (i == 5)
3640 lvalue = true;
3641 break;
3642 case glslang::EOpSparseTextureGradOffsetClamp:
3643 if (i == 6)
3644 lvalue = true;
3645 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003646#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003647 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003648 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3649 lvalue = true;
3650 break;
3651 case glslang::EOpSparseTextureGatherOffset:
3652 case glslang::EOpSparseTextureGatherOffsets:
3653 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3654 lvalue = true;
3655 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003656#ifdef AMD_EXTENSIONS
3657 case glslang::EOpSparseTextureGatherLod:
3658 if (i == 3)
3659 lvalue = true;
3660 break;
3661 case glslang::EOpSparseTextureGatherLodOffset:
3662 case glslang::EOpSparseTextureGatherLodOffsets:
3663 if (i == 4)
3664 lvalue = true;
3665 break;
Rex Xu129799a2017-07-05 17:23:28 +08003666 case glslang::EOpSparseImageLoadLod:
3667 if (i == 3)
3668 lvalue = true;
3669 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003670#endif
Chao Chen3a137962018-09-19 11:41:27 -07003671#ifdef NV_EXTENSIONS
3672 case glslang::EOpImageSampleFootprintNV:
3673 if (i == 4)
3674 lvalue = true;
3675 break;
3676 case glslang::EOpImageSampleFootprintClampNV:
3677 case glslang::EOpImageSampleFootprintLodNV:
3678 if (i == 5)
3679 lvalue = true;
3680 break;
3681 case glslang::EOpImageSampleFootprintGradNV:
3682 if (i == 6)
3683 lvalue = true;
3684 break;
3685 case glslang::EOpImageSampleFootprintGradClampNV:
3686 if (i == 7)
3687 lvalue = true;
3688 break;
3689#endif
Rex Xufc618912015-09-09 16:42:49 +08003690 default:
3691 break;
3692 }
3693
Rex Xu6b86d492015-09-16 17:48:22 +08003694 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003695 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003696 else
John Kessenich32cfd492016-02-02 12:37:46 -07003697 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003698 }
3699}
3700
John Kessenichfc51d282015-08-19 13:34:18 -06003701void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003702{
John Kessenichfc51d282015-08-19 13:34:18 -06003703 builder.clearAccessChain();
3704 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003705 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003706}
John Kessenich140f3df2015-06-26 16:58:36 -06003707
John Kessenichfc51d282015-08-19 13:34:18 -06003708spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3709{
John Kesseniche485c7a2017-05-31 18:50:53 -06003710 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003711 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003712
3713 builder.setLine(node->getLoc().line);
3714
John Kessenichfc51d282015-08-19 13:34:18 -06003715 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003716
3717 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3718 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3719 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003720#ifdef AMD_EXTENSIONS
3721 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3722 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3723 : false;
3724#endif
3725
John Kessenichfc51d282015-08-19 13:34:18 -06003726 std::vector<spv::Id> arguments;
3727 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003728 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003729 else
3730 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003731 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003732
3733 spv::Builder::TextureParameters params = { };
3734 params.sampler = arguments[0];
3735
Rex Xu04db3f52015-09-16 11:44:02 +08003736 glslang::TCrackedTextureOp cracked;
3737 node->crackTexture(sampler, cracked);
3738
amhagan05506bb2017-06-13 16:53:02 -04003739 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003740
John Kessenichfc51d282015-08-19 13:34:18 -06003741 // Check for queries
3742 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003743 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3744 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003745 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003746
John Kessenichfc51d282015-08-19 13:34:18 -06003747 switch (node->getOp()) {
3748 case glslang::EOpImageQuerySize:
3749 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003750 if (arguments.size() > 1) {
3751 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003752 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003754 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003755 case glslang::EOpImageQuerySamples:
3756 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003757 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003758 case glslang::EOpTextureQueryLod:
3759 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003760 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003761 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003762 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003763 case glslang::EOpSparseTexelsResident:
3764 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003765 default:
3766 assert(0);
3767 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 }
John Kessenich140f3df2015-06-26 16:58:36 -06003769 }
3770
LoopDawg4425f242018-02-18 11:40:01 -07003771 int components = node->getType().getVectorSize();
3772
3773 if (node->getOp() == glslang::EOpTextureFetch) {
3774 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3775 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3776 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3777 // here around e.g. which ones return scalars or other types.
3778 components = 4;
3779 }
3780
3781 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3782
3783 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3784
Rex Xufc618912015-09-09 16:42:49 +08003785 // Check for image functions other than queries
3786 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003787 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003788 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003789 spv::IdImmediate image = { true, *(opIt++) };
3790 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003791
3792 // Handle subpass operations
3793 // TODO: GLSL should change to have the "MS" only on the type rather than the
3794 // built-in function.
3795 if (cracked.subpass) {
3796 // add on the (0,0) coordinate
3797 spv::Id zero = builder.makeIntConstant(0);
3798 std::vector<spv::Id> comps;
3799 comps.push_back(zero);
3800 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003801 spv::IdImmediate coord = { true,
3802 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3803 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003804 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003805 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3806 operands.push_back(imageOperands);
3807 spv::IdImmediate imageOperand = { true, *(opIt++) };
3808 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003809 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003810 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3811 builder.setPrecision(result, precision);
3812 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003813 }
3814
John Kessenich149afc32018-08-14 13:31:43 -06003815 spv::IdImmediate coord = { true, *(opIt++) };
3816 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003817#ifdef AMD_EXTENSIONS
3818 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3819#else
John Kessenich56bab042015-09-16 10:54:31 -06003820 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003821#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003822 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003823 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003824 mask = mask | spv::ImageOperandsSampleMask;
3825 }
Rex Xu129799a2017-07-05 17:23:28 +08003826#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003827 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003828 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3829 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003830 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003831 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003832#endif
3833 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3834 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3835 if (mask) {
3836 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3837 operands.push_back(imageOperands);
3838 }
3839 if (mask & spv::ImageOperandsSampleMask) {
3840 spv::IdImmediate imageOperand = { true, *opIt++ };
3841 operands.push_back(imageOperand);
3842 }
3843#ifdef AMD_EXTENSIONS
3844 if (mask & spv::ImageOperandsLodMask) {
3845 spv::IdImmediate imageOperand = { true, *opIt++ };
3846 operands.push_back(imageOperand);
3847 }
3848#endif
3849 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3850 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3851 operands.push_back(imageOperand);
3852 }
3853
John Kessenich149afc32018-08-14 13:31:43 -06003854 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003855 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003856
John Kessenich149afc32018-08-14 13:31:43 -06003857 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003858 builder.setPrecision(result[0], precision);
3859
3860 // If needed, add a conversion constructor to the proper size.
3861 if (components != node->getType().getVectorSize())
3862 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3863
3864 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003865#ifdef AMD_EXTENSIONS
3866 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3867#else
John Kessenich56bab042015-09-16 10:54:31 -06003868 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003869#endif
Rex Xu129799a2017-07-05 17:23:28 +08003870
Jeff Bolz36831c92018-09-05 10:11:41 -05003871 // Push the texel value before the operands
3872#ifdef AMD_EXTENSIONS
3873 if (sampler.ms || cracked.lod) {
3874#else
3875 if (sampler.ms) {
3876#endif
John Kessenich149afc32018-08-14 13:31:43 -06003877 spv::IdImmediate texel = { true, *(opIt + 1) };
3878 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003879 } else {
3880 spv::IdImmediate texel = { true, *opIt };
3881 operands.push_back(texel);
3882 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003883
3884 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3885 if (sampler.ms) {
3886 mask = mask | spv::ImageOperandsSampleMask;
3887 }
3888#ifdef AMD_EXTENSIONS
3889 if (cracked.lod) {
3890 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3891 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3892 mask = mask | spv::ImageOperandsLodMask;
3893 }
3894#endif
3895 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3896 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3897 if (mask) {
3898 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3899 operands.push_back(imageOperands);
3900 }
3901 if (mask & spv::ImageOperandsSampleMask) {
3902 spv::IdImmediate imageOperand = { true, *opIt++ };
3903 operands.push_back(imageOperand);
3904 }
3905#ifdef AMD_EXTENSIONS
3906 if (mask & spv::ImageOperandsLodMask) {
3907 spv::IdImmediate imageOperand = { true, *opIt++ };
3908 operands.push_back(imageOperand);
3909 }
3910#endif
3911 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
3912 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3913 operands.push_back(imageOperand);
3914 }
3915
John Kessenich56bab042015-09-16 10:54:31 -06003916 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003917 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003918 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003919 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003920#ifdef AMD_EXTENSIONS
3921 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3922#else
Rex Xu5eafa472016-02-19 22:24:03 +08003923 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003924#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003925 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003926 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003927 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3928
Jeff Bolz36831c92018-09-05 10:11:41 -05003929 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08003930 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003931 mask = mask | spv::ImageOperandsSampleMask;
3932 }
Rex Xu129799a2017-07-05 17:23:28 +08003933#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003934 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003935 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3936 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3937
Jeff Bolz36831c92018-09-05 10:11:41 -05003938 mask = mask | spv::ImageOperandsLodMask;
3939 }
3940#endif
3941 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3942 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3943 if (mask) {
3944 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06003945 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05003946 }
3947 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06003948 spv::IdImmediate imageOperand = { true, *opIt++ };
3949 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05003950 }
3951#ifdef AMD_EXTENSIONS
3952 if (mask & spv::ImageOperandsLodMask) {
3953 spv::IdImmediate imageOperand = { true, *opIt++ };
3954 operands.push_back(imageOperand);
3955 }
Rex Xu129799a2017-07-05 17:23:28 +08003956#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003957 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3958 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3959 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08003960 }
3961
3962 // Create the return type that was a special structure
3963 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003964 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003965 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3966 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3967
3968 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3969
3970 // Decode the return type
3971 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3972 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003973 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003974 // Process image atomic operations
3975
3976 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3977 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003978 // For non-MS, the sample value should be 0
3979 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3980 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003981
Jeff Bolz36831c92018-09-05 10:11:41 -05003982 spv::Id resultTypeId;
3983 // imageAtomicStore has a void return type so base the pointer type on
3984 // the type of the value operand.
3985 if (node->getOp() == glslang::EOpImageAtomicStore) {
3986 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
3987 } else {
3988 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
3989 }
John Kessenich56bab042015-09-16 10:54:31 -06003990 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003991
3992 std::vector<spv::Id> operands;
3993 operands.push_back(pointer);
3994 for (; opIt != arguments.end(); ++opIt)
3995 operands.push_back(*opIt);
3996
John Kessenich8c8505c2016-07-26 12:50:38 -06003997 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003998 }
3999 }
4000
amhagan05506bb2017-06-13 16:53:02 -04004001#ifdef AMD_EXTENSIONS
4002 // Check for fragment mask functions other than queries
4003 if (cracked.fragMask) {
4004 assert(sampler.ms);
4005
4006 auto opIt = arguments.begin();
4007 std::vector<spv::Id> operands;
4008
4009 // Extract the image if necessary
4010 if (builder.isSampledImage(params.sampler))
4011 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4012
4013 operands.push_back(params.sampler);
4014 ++opIt;
4015
4016 if (sampler.isSubpass()) {
4017 // add on the (0,0) coordinate
4018 spv::Id zero = builder.makeIntConstant(0);
4019 std::vector<spv::Id> comps;
4020 comps.push_back(zero);
4021 comps.push_back(zero);
4022 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4023 }
4024
4025 for (; opIt != arguments.end(); ++opIt)
4026 operands.push_back(*opIt);
4027
4028 spv::Op fragMaskOp = spv::OpNop;
4029 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4030 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4031 else if (node->getOp() == glslang::EOpFragmentFetch)
4032 fragMaskOp = spv::OpFragmentFetchAMD;
4033
4034 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4035 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4036 return builder.createOp(fragMaskOp, resultType(), operands);
4037 }
4038#endif
4039
Rex Xufc618912015-09-09 16:42:49 +08004040 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004041 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004042#ifdef NV_EXTENSIONS
4043 bool imageFootprint = node->isImageFootprint();
4044#endif
4045
Rex Xu71519fe2015-11-11 15:35:47 +08004046 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4047
John Kessenichfc51d282015-08-19 13:34:18 -06004048 // check for bias argument
4049 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004050#ifdef AMD_EXTENSIONS
4051 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4052#else
Rex Xu71519fe2015-11-11 15:35:47 +08004053 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004054#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004055 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004056#ifdef AMD_EXTENSIONS
4057 if (cracked.gather)
4058 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004059
4060 if (f16ShadowCompare)
4061 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004062#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004063 if (cracked.offset)
4064 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004065#ifdef AMD_EXTENSIONS
4066 else if (cracked.offsets)
4067 ++nonBiasArgCount;
4068#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004069 if (cracked.grad)
4070 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004071 if (cracked.lodClamp)
4072 ++nonBiasArgCount;
4073 if (sparse)
4074 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004075#ifdef NV_EXTENSIONS
4076 if (imageFootprint)
4077 //Following three extra arguments
4078 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4079 nonBiasArgCount += 3;
4080#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004081 if ((int)arguments.size() > nonBiasArgCount)
4082 bias = true;
4083 }
4084
John Kessenicha5c33d62016-06-02 23:45:21 -06004085 // See if the sampler param should really be just the SPV image part
4086 if (cracked.fetch) {
4087 // a fetch needs to have the image extracted first
4088 if (builder.isSampledImage(params.sampler))
4089 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4090 }
4091
Rex Xu225e0fc2016-11-17 17:47:59 +08004092#ifdef AMD_EXTENSIONS
4093 if (cracked.gather) {
4094 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4095 if (bias || cracked.lod ||
4096 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4097 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004098 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004099 }
4100 }
4101#endif
4102
John Kessenichfc51d282015-08-19 13:34:18 -06004103 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004104
John Kessenichfc51d282015-08-19 13:34:18 -06004105 params.coords = arguments[1];
4106 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004107 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004108
4109 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004110#ifdef AMD_EXTENSIONS
4111 if (cubeCompare || f16ShadowCompare) {
4112#else
Rex Xu48edadf2015-12-31 16:11:41 +08004113 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004114#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004115 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004116 ++extraArgs;
4117 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004118 params.Dref = arguments[2];
4119 ++extraArgs;
4120 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004121 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004122 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004123 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004124 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004125 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004126 dRefComp = builder.getNumComponents(params.coords) - 1;
4127 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004128 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004130
4131 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004132 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004133 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004134 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004135 } else if (glslangIntermediate->getStage() != EShLangFragment
4136#ifdef NV_EXTENSIONS
4137 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4138 && !(glslangIntermediate->getStage() == EShLangCompute &&
4139 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4140#endif
4141 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004142 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4143 noImplicitLod = true;
4144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004145
4146 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004147 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004148 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004149 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004150 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004151
4152 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004153 if (cracked.grad) {
4154 params.gradX = arguments[2 + extraArgs];
4155 params.gradY = arguments[3 + extraArgs];
4156 extraArgs += 2;
4157 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004158
4159 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004160 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004161 params.offset = arguments[2 + extraArgs];
4162 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004163 } else if (cracked.offsets) {
4164 params.offsets = arguments[2 + extraArgs];
4165 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004166 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004167
4168 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004169 if (cracked.lodClamp) {
4170 params.lodClamp = arguments[2 + extraArgs];
4171 ++extraArgs;
4172 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004173 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004174 if (sparse) {
4175 params.texelOut = arguments[2 + extraArgs];
4176 ++extraArgs;
4177 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004178
John Kessenich76d4dfc2016-06-16 12:43:23 -06004179 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004180 if (cracked.gather && ! sampler.shadow) {
4181 // default component is 0, if missing, otherwise an argument
4182 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004183 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004184 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004185 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004186 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004187 }
Chao Chen3a137962018-09-19 11:41:27 -07004188#ifdef NV_EXTENSIONS
4189 spv::Id resultStruct = spv::NoResult;
4190 if (imageFootprint) {
4191 //Following three extra arguments
4192 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4193 params.granularity = arguments[2 + extraArgs];
4194 params.coarse = arguments[3 + extraArgs];
4195 resultStruct = arguments[4 + extraArgs];
4196 extraArgs += 3;
4197 }
4198#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004199 // bias
4200 if (bias) {
4201 params.bias = arguments[2 + extraArgs];
4202 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004203 }
John Kessenichfc51d282015-08-19 13:34:18 -06004204
Chao Chen3a137962018-09-19 11:41:27 -07004205#ifdef NV_EXTENSIONS
4206 if (imageFootprint) {
4207 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4208 builder.addCapability(spv::CapabilityImageFootprintNV);
4209
4210
4211 //resultStructType(OpenGL type) contains 5 elements:
4212 //struct gl_TextureFootprint2DNV {
4213 // uvec2 anchor;
4214 // uvec2 offset;
4215 // uvec2 mask;
4216 // uint lod;
4217 // uint granularity;
4218 //};
4219 //or
4220 //struct gl_TextureFootprint3DNV {
4221 // uvec3 anchor;
4222 // uvec3 offset;
4223 // uvec2 mask;
4224 // uint lod;
4225 // uint granularity;
4226 //};
4227 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4228 assert(builder.isStructType(resultStructType));
4229
4230 //resType (SPIR-V type) contains 6 elements:
4231 //Member 0 must be a Boolean type scalar(LOD),
4232 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4233 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4234 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4235 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4236 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4237 std::vector<spv::Id> members;
4238 members.push_back(resultType());
4239 for (int i = 0; i < 5; i++) {
4240 members.push_back(builder.getContainedTypeId(resultStructType, i));
4241 }
4242 spv::Id resType = builder.makeStructType(members, "ResType");
4243
4244 //call ImageFootprintNV
4245 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4246
4247 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4248 for (int i = 0; i < 5; i++) {
4249 builder.clearAccessChain();
4250 builder.setAccessChainLValue(resultStruct);
4251
4252 //Accessing to a struct we created, no coherent flag is set
4253 spv::Builder::AccessChain::CoherentFlags flags;
4254 flags.clear();
4255
4256 builder.accessChainPush(builder.makeIntConstant(i), flags);
4257 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4258 }
4259 return builder.createCompositeExtract(res, resultType(), 0);
4260 }
4261#endif
4262
John Kessenich65336482016-06-16 14:06:26 -06004263 // projective component (might not to move)
4264 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4265 // are divided by the last component of P."
4266 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4267 // unused components will appear after all used components."
4268 if (cracked.proj) {
4269 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4270 int projTargetComp;
4271 switch (sampler.dim) {
4272 case glslang::Esd1D: projTargetComp = 1; break;
4273 case glslang::Esd2D: projTargetComp = 2; break;
4274 case glslang::EsdRect: projTargetComp = 2; break;
4275 default: projTargetComp = projSourceComp; break;
4276 }
4277 // copy the projective coordinate if we have to
4278 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004279 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004280 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4281 projSourceComp);
4282 params.coords = builder.createCompositeInsert(projComp, params.coords,
4283 builder.getTypeId(params.coords), projTargetComp);
4284 }
4285 }
4286
Jeff Bolz36831c92018-09-05 10:11:41 -05004287 // nonprivate
4288 if (imageType.getQualifier().nonprivate) {
4289 params.nonprivate = true;
4290 }
4291
4292 // volatile
4293 if (imageType.getQualifier().volatil) {
4294 params.volatil = true;
4295 }
4296
St0fFa1184dd2018-04-09 21:08:14 +02004297 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004298 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004299 );
LoopDawg4425f242018-02-18 11:40:01 -07004300
4301 if (components != node->getType().getVectorSize())
4302 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4303
4304 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004305}
4306
4307spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4308{
4309 // Grab the function's pointer from the previously created function
4310 spv::Function* function = functionMap[node->getName().c_str()];
4311 if (! function)
4312 return 0;
4313
4314 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4315 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4316
4317 // See comments in makeFunctions() for details about the semantics for parameter passing.
4318 //
4319 // These imply we need a four step process:
4320 // 1. Evaluate the arguments
4321 // 2. Allocate and make copies of in, out, and inout arguments
4322 // 3. Make the call
4323 // 4. Copy back the results
4324
John Kessenichd3ed90b2018-05-04 11:43:03 -06004325 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004326 std::vector<spv::Builder::AccessChain> lValues;
4327 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004328 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004329 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004330 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004331 // build l-value
4332 builder.clearAccessChain();
4333 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004334 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004335 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004336 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004337 // save l-value
4338 lValues.push_back(builder.getAccessChain());
4339 } else {
4340 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004341 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004342 }
4343 }
4344
4345 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4346 // copy the original into that space.
4347 //
4348 // Also, build up the list of actual arguments to pass in for the call
4349 int lValueCount = 0;
4350 int rValueCount = 0;
4351 std::vector<spv::Id> spvArgs;
4352 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4353 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004354 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004355 builder.setAccessChain(lValues[lValueCount]);
4356 arg = builder.accessChainGetLValue();
4357 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004358 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004359 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004360 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004361 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4362 // need to copy the input into output space
4363 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004364 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004365 builder.clearAccessChain();
4366 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004367 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004368 }
4369 ++lValueCount;
4370 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004371 // process r-value, which involves a copy for a type mismatch
4372 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4373 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4374 builder.clearAccessChain();
4375 builder.setAccessChainLValue(argCopy);
4376 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4377 arg = builder.createLoad(argCopy);
4378 } else
4379 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004380 ++rValueCount;
4381 }
4382 spvArgs.push_back(arg);
4383 }
4384
4385 // 3. Make the call.
4386 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004387 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004388
4389 // 4. Copy back out an "out" arguments.
4390 lValueCount = 0;
4391 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004392 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004393 ++lValueCount;
4394 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004395 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4396 spv::Id copy = builder.createLoad(spvArgs[a]);
4397 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004398 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004399 }
4400 ++lValueCount;
4401 }
4402 }
4403
4404 return result;
4405}
4406
4407// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004408spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004409 spv::Id typeId, spv::Id left, spv::Id right,
4410 glslang::TBasicType typeProxy, bool reduceComparison)
4411{
John Kessenich66011cb2018-03-06 16:12:04 -07004412 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4413 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004414 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004415
4416 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004417 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004418 bool comparison = false;
4419
4420 switch (op) {
4421 case glslang::EOpAdd:
4422 case glslang::EOpAddAssign:
4423 if (isFloat)
4424 binOp = spv::OpFAdd;
4425 else
4426 binOp = spv::OpIAdd;
4427 break;
4428 case glslang::EOpSub:
4429 case glslang::EOpSubAssign:
4430 if (isFloat)
4431 binOp = spv::OpFSub;
4432 else
4433 binOp = spv::OpISub;
4434 break;
4435 case glslang::EOpMul:
4436 case glslang::EOpMulAssign:
4437 if (isFloat)
4438 binOp = spv::OpFMul;
4439 else
4440 binOp = spv::OpIMul;
4441 break;
4442 case glslang::EOpVectorTimesScalar:
4443 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004444 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004445 if (builder.isVector(right))
4446 std::swap(left, right);
4447 assert(builder.isScalar(right));
4448 needMatchingVectors = false;
4449 binOp = spv::OpVectorTimesScalar;
4450 } else
4451 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004452 break;
4453 case glslang::EOpVectorTimesMatrix:
4454 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004455 binOp = spv::OpVectorTimesMatrix;
4456 break;
4457 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004458 binOp = spv::OpMatrixTimesVector;
4459 break;
4460 case glslang::EOpMatrixTimesScalar:
4461 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004462 binOp = spv::OpMatrixTimesScalar;
4463 break;
4464 case glslang::EOpMatrixTimesMatrix:
4465 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004466 binOp = spv::OpMatrixTimesMatrix;
4467 break;
4468 case glslang::EOpOuterProduct:
4469 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004470 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004471 break;
4472
4473 case glslang::EOpDiv:
4474 case glslang::EOpDivAssign:
4475 if (isFloat)
4476 binOp = spv::OpFDiv;
4477 else if (isUnsigned)
4478 binOp = spv::OpUDiv;
4479 else
4480 binOp = spv::OpSDiv;
4481 break;
4482 case glslang::EOpMod:
4483 case glslang::EOpModAssign:
4484 if (isFloat)
4485 binOp = spv::OpFMod;
4486 else if (isUnsigned)
4487 binOp = spv::OpUMod;
4488 else
4489 binOp = spv::OpSMod;
4490 break;
4491 case glslang::EOpRightShift:
4492 case glslang::EOpRightShiftAssign:
4493 if (isUnsigned)
4494 binOp = spv::OpShiftRightLogical;
4495 else
4496 binOp = spv::OpShiftRightArithmetic;
4497 break;
4498 case glslang::EOpLeftShift:
4499 case glslang::EOpLeftShiftAssign:
4500 binOp = spv::OpShiftLeftLogical;
4501 break;
4502 case glslang::EOpAnd:
4503 case glslang::EOpAndAssign:
4504 binOp = spv::OpBitwiseAnd;
4505 break;
4506 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004507 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 binOp = spv::OpLogicalAnd;
4509 break;
4510 case glslang::EOpInclusiveOr:
4511 case glslang::EOpInclusiveOrAssign:
4512 binOp = spv::OpBitwiseOr;
4513 break;
4514 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004515 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004516 binOp = spv::OpLogicalOr;
4517 break;
4518 case glslang::EOpExclusiveOr:
4519 case glslang::EOpExclusiveOrAssign:
4520 binOp = spv::OpBitwiseXor;
4521 break;
4522 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004523 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004524 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004525 break;
4526
4527 case glslang::EOpLessThan:
4528 case glslang::EOpGreaterThan:
4529 case glslang::EOpLessThanEqual:
4530 case glslang::EOpGreaterThanEqual:
4531 case glslang::EOpEqual:
4532 case glslang::EOpNotEqual:
4533 case glslang::EOpVectorEqual:
4534 case glslang::EOpVectorNotEqual:
4535 comparison = true;
4536 break;
4537 default:
4538 break;
4539 }
4540
John Kessenich7c1aa102015-10-15 13:29:11 -06004541 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004542 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004543 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004544 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004545 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004546
4547 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004548 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004549 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004550
qining25262b32016-05-06 17:25:16 -04004551 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004552 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004553 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004554 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004555 }
4556
4557 if (! comparison)
4558 return 0;
4559
John Kessenich7c1aa102015-10-15 13:29:11 -06004560 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004561
John Kessenich4583b612016-08-07 19:14:22 -06004562 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004563 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4564 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004565 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004566 return result;
4567 }
John Kessenich140f3df2015-06-26 16:58:36 -06004568
4569 switch (op) {
4570 case glslang::EOpLessThan:
4571 if (isFloat)
4572 binOp = spv::OpFOrdLessThan;
4573 else if (isUnsigned)
4574 binOp = spv::OpULessThan;
4575 else
4576 binOp = spv::OpSLessThan;
4577 break;
4578 case glslang::EOpGreaterThan:
4579 if (isFloat)
4580 binOp = spv::OpFOrdGreaterThan;
4581 else if (isUnsigned)
4582 binOp = spv::OpUGreaterThan;
4583 else
4584 binOp = spv::OpSGreaterThan;
4585 break;
4586 case glslang::EOpLessThanEqual:
4587 if (isFloat)
4588 binOp = spv::OpFOrdLessThanEqual;
4589 else if (isUnsigned)
4590 binOp = spv::OpULessThanEqual;
4591 else
4592 binOp = spv::OpSLessThanEqual;
4593 break;
4594 case glslang::EOpGreaterThanEqual:
4595 if (isFloat)
4596 binOp = spv::OpFOrdGreaterThanEqual;
4597 else if (isUnsigned)
4598 binOp = spv::OpUGreaterThanEqual;
4599 else
4600 binOp = spv::OpSGreaterThanEqual;
4601 break;
4602 case glslang::EOpEqual:
4603 case glslang::EOpVectorEqual:
4604 if (isFloat)
4605 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004606 else if (isBool)
4607 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004608 else
4609 binOp = spv::OpIEqual;
4610 break;
4611 case glslang::EOpNotEqual:
4612 case glslang::EOpVectorNotEqual:
4613 if (isFloat)
4614 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004615 else if (isBool)
4616 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004617 else
4618 binOp = spv::OpINotEqual;
4619 break;
4620 default:
4621 break;
4622 }
4623
qining25262b32016-05-06 17:25:16 -04004624 if (binOp != spv::OpNop) {
4625 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004626 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004627 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004628 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004629 }
John Kessenich140f3df2015-06-26 16:58:36 -06004630
4631 return 0;
4632}
4633
John Kessenich04bb8a02015-12-12 12:28:14 -07004634//
4635// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4636// These can be any of:
4637//
4638// matrix * scalar
4639// scalar * matrix
4640// matrix * matrix linear algebraic
4641// matrix * vector
4642// vector * matrix
4643// matrix * matrix componentwise
4644// matrix op matrix op in {+, -, /}
4645// matrix op scalar op in {+, -, /}
4646// scalar op matrix op in {+, -, /}
4647//
John Kessenichead86222018-03-28 18:01:20 -06004648spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4649 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004650{
4651 bool firstClass = true;
4652
4653 // First, handle first-class matrix operations (* and matrix/scalar)
4654 switch (op) {
4655 case spv::OpFDiv:
4656 if (builder.isMatrix(left) && builder.isScalar(right)) {
4657 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004658 spv::Id resultType = builder.getTypeId(right);
4659 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004660 op = spv::OpMatrixTimesScalar;
4661 } else
4662 firstClass = false;
4663 break;
4664 case spv::OpMatrixTimesScalar:
4665 if (builder.isMatrix(right))
4666 std::swap(left, right);
4667 assert(builder.isScalar(right));
4668 break;
4669 case spv::OpVectorTimesMatrix:
4670 assert(builder.isVector(left));
4671 assert(builder.isMatrix(right));
4672 break;
4673 case spv::OpMatrixTimesVector:
4674 assert(builder.isMatrix(left));
4675 assert(builder.isVector(right));
4676 break;
4677 case spv::OpMatrixTimesMatrix:
4678 assert(builder.isMatrix(left));
4679 assert(builder.isMatrix(right));
4680 break;
4681 default:
4682 firstClass = false;
4683 break;
4684 }
4685
qining25262b32016-05-06 17:25:16 -04004686 if (firstClass) {
4687 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004688 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004689 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004690 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004691 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004692
LoopDawg592860c2016-06-09 08:57:35 -06004693 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004694 // The result type of all of them is the same type as the (a) matrix operand.
4695 // The algorithm is to:
4696 // - break the matrix(es) into vectors
4697 // - smear any scalar to a vector
4698 // - do vector operations
4699 // - make a matrix out the vector results
4700 switch (op) {
4701 case spv::OpFAdd:
4702 case spv::OpFSub:
4703 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004704 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004705 case spv::OpFMul:
4706 {
4707 // one time set up...
4708 bool leftMat = builder.isMatrix(left);
4709 bool rightMat = builder.isMatrix(right);
4710 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4711 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4712 spv::Id scalarType = builder.getScalarTypeId(typeId);
4713 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4714 std::vector<spv::Id> results;
4715 spv::Id smearVec = spv::NoResult;
4716 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004717 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004718 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004719 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004720
4721 // do each vector op
4722 for (unsigned int c = 0; c < numCols; ++c) {
4723 std::vector<unsigned int> indexes;
4724 indexes.push_back(c);
4725 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4726 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004727 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004728 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004729 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004730 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004731 }
4732
4733 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004734 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004735 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004736 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004737 }
4738 default:
4739 assert(0);
4740 return spv::NoResult;
4741 }
4742}
4743
John Kessenichead86222018-03-28 18:01:20 -06004744spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4745 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004746{
4747 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004748 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004749 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004750 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4751 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004752
4753 switch (op) {
4754 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004755 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004756 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004757 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004758 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004759 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004760 unaryOp = spv::OpSNegate;
4761 break;
4762
4763 case glslang::EOpLogicalNot:
4764 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004765 unaryOp = spv::OpLogicalNot;
4766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004767 case glslang::EOpBitwiseNot:
4768 unaryOp = spv::OpNot;
4769 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004770
John Kessenich140f3df2015-06-26 16:58:36 -06004771 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004772 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004773 break;
4774 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004775 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004776 break;
4777 case glslang::EOpTranspose:
4778 unaryOp = spv::OpTranspose;
4779 break;
4780
4781 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004782 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004783 break;
4784 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004785 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004786 break;
4787 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004788 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004789 break;
4790 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004791 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 break;
4793 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004794 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004795 break;
4796 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004797 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004798 break;
4799 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004800 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004801 break;
4802 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004803 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004804 break;
4805
4806 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004807 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004808 break;
4809 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004810 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004811 break;
4812 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004813 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004814 break;
4815 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004816 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004817 break;
4818 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004819 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004820 break;
4821 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004822 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004823 break;
4824
4825 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004826 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004827 break;
4828 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004829 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004830 break;
4831
4832 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004833 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004834 break;
4835 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004836 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004837 break;
4838 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004839 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004840 break;
4841 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004842 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004843 break;
4844 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004845 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004846 break;
4847 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004848 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004849 break;
4850
4851 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004852 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004853 break;
4854 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004855 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004856 break;
4857 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004858 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004859 break;
4860 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004861 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004862 break;
4863 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004864 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004865 break;
4866 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004867 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004868 break;
4869
4870 case glslang::EOpIsNan:
4871 unaryOp = spv::OpIsNan;
4872 break;
4873 case glslang::EOpIsInf:
4874 unaryOp = spv::OpIsInf;
4875 break;
LoopDawg592860c2016-06-09 08:57:35 -06004876 case glslang::EOpIsFinite:
4877 unaryOp = spv::OpIsFinite;
4878 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004879
Rex Xucbc426e2015-12-15 16:03:10 +08004880 case glslang::EOpFloatBitsToInt:
4881 case glslang::EOpFloatBitsToUint:
4882 case glslang::EOpIntBitsToFloat:
4883 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004884 case glslang::EOpDoubleBitsToInt64:
4885 case glslang::EOpDoubleBitsToUint64:
4886 case glslang::EOpInt64BitsToDouble:
4887 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004888 case glslang::EOpFloat16BitsToInt16:
4889 case glslang::EOpFloat16BitsToUint16:
4890 case glslang::EOpInt16BitsToFloat16:
4891 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004892 unaryOp = spv::OpBitcast;
4893 break;
4894
John Kessenich140f3df2015-06-26 16:58:36 -06004895 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004896 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004897 break;
4898 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004899 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004900 break;
4901 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004902 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004903 break;
4904 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004905 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004906 break;
4907 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004908 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004909 break;
4910 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004911 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004912 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004913 case glslang::EOpPackSnorm4x8:
4914 libCall = spv::GLSLstd450PackSnorm4x8;
4915 break;
4916 case glslang::EOpUnpackSnorm4x8:
4917 libCall = spv::GLSLstd450UnpackSnorm4x8;
4918 break;
4919 case glslang::EOpPackUnorm4x8:
4920 libCall = spv::GLSLstd450PackUnorm4x8;
4921 break;
4922 case glslang::EOpUnpackUnorm4x8:
4923 libCall = spv::GLSLstd450UnpackUnorm4x8;
4924 break;
4925 case glslang::EOpPackDouble2x32:
4926 libCall = spv::GLSLstd450PackDouble2x32;
4927 break;
4928 case glslang::EOpUnpackDouble2x32:
4929 libCall = spv::GLSLstd450UnpackDouble2x32;
4930 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004931
Rex Xu8ff43de2016-04-22 16:51:45 +08004932 case glslang::EOpPackInt2x32:
4933 case glslang::EOpUnpackInt2x32:
4934 case glslang::EOpPackUint2x32:
4935 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004936 case glslang::EOpPack16:
4937 case glslang::EOpPack32:
4938 case glslang::EOpPack64:
4939 case glslang::EOpUnpack32:
4940 case glslang::EOpUnpack16:
4941 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004942 case glslang::EOpPackInt2x16:
4943 case glslang::EOpUnpackInt2x16:
4944 case glslang::EOpPackUint2x16:
4945 case glslang::EOpUnpackUint2x16:
4946 case glslang::EOpPackInt4x16:
4947 case glslang::EOpUnpackInt4x16:
4948 case glslang::EOpPackUint4x16:
4949 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004950 case glslang::EOpPackFloat2x16:
4951 case glslang::EOpUnpackFloat2x16:
4952 unaryOp = spv::OpBitcast;
4953 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004954
John Kessenich140f3df2015-06-26 16:58:36 -06004955 case glslang::EOpDPdx:
4956 unaryOp = spv::OpDPdx;
4957 break;
4958 case glslang::EOpDPdy:
4959 unaryOp = spv::OpDPdy;
4960 break;
4961 case glslang::EOpFwidth:
4962 unaryOp = spv::OpFwidth;
4963 break;
4964 case glslang::EOpDPdxFine:
4965 unaryOp = spv::OpDPdxFine;
4966 break;
4967 case glslang::EOpDPdyFine:
4968 unaryOp = spv::OpDPdyFine;
4969 break;
4970 case glslang::EOpFwidthFine:
4971 unaryOp = spv::OpFwidthFine;
4972 break;
4973 case glslang::EOpDPdxCoarse:
4974 unaryOp = spv::OpDPdxCoarse;
4975 break;
4976 case glslang::EOpDPdyCoarse:
4977 unaryOp = spv::OpDPdyCoarse;
4978 break;
4979 case glslang::EOpFwidthCoarse:
4980 unaryOp = spv::OpFwidthCoarse;
4981 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004982 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004983#ifdef AMD_EXTENSIONS
4984 if (typeProxy == glslang::EbtFloat16)
4985 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4986#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004987 libCall = spv::GLSLstd450InterpolateAtCentroid;
4988 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 case glslang::EOpAny:
4990 unaryOp = spv::OpAny;
4991 break;
4992 case glslang::EOpAll:
4993 unaryOp = spv::OpAll;
4994 break;
4995
4996 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004997 if (isFloat)
4998 libCall = spv::GLSLstd450FAbs;
4999 else
5000 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005001 break;
5002 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005003 if (isFloat)
5004 libCall = spv::GLSLstd450FSign;
5005 else
5006 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005007 break;
5008
John Kessenichfc51d282015-08-19 13:34:18 -06005009 case glslang::EOpAtomicCounterIncrement:
5010 case glslang::EOpAtomicCounterDecrement:
5011 case glslang::EOpAtomicCounter:
5012 {
5013 // Handle all of the atomics in one place, in createAtomicOperation()
5014 std::vector<spv::Id> operands;
5015 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005016 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005017 }
5018
John Kessenichfc51d282015-08-19 13:34:18 -06005019 case glslang::EOpBitFieldReverse:
5020 unaryOp = spv::OpBitReverse;
5021 break;
5022 case glslang::EOpBitCount:
5023 unaryOp = spv::OpBitCount;
5024 break;
5025 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005026 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005027 break;
5028 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005029 if (isUnsigned)
5030 libCall = spv::GLSLstd450FindUMsb;
5031 else
5032 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005033 break;
5034
Rex Xu574ab042016-04-14 16:53:07 +08005035 case glslang::EOpBallot:
5036 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005037 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005038 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005039 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005040#ifdef AMD_EXTENSIONS
5041 case glslang::EOpMinInvocations:
5042 case glslang::EOpMaxInvocations:
5043 case glslang::EOpAddInvocations:
5044 case glslang::EOpMinInvocationsNonUniform:
5045 case glslang::EOpMaxInvocationsNonUniform:
5046 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005047 case glslang::EOpMinInvocationsInclusiveScan:
5048 case glslang::EOpMaxInvocationsInclusiveScan:
5049 case glslang::EOpAddInvocationsInclusiveScan:
5050 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5051 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5052 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5053 case glslang::EOpMinInvocationsExclusiveScan:
5054 case glslang::EOpMaxInvocationsExclusiveScan:
5055 case glslang::EOpAddInvocationsExclusiveScan:
5056 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5057 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5058 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005059#endif
Rex Xu51596642016-09-21 18:56:12 +08005060 {
5061 std::vector<spv::Id> operands;
5062 operands.push_back(operand);
5063 return createInvocationsOperation(op, typeId, operands, typeProxy);
5064 }
John Kessenich66011cb2018-03-06 16:12:04 -07005065 case glslang::EOpSubgroupAll:
5066 case glslang::EOpSubgroupAny:
5067 case glslang::EOpSubgroupAllEqual:
5068 case glslang::EOpSubgroupBroadcastFirst:
5069 case glslang::EOpSubgroupBallot:
5070 case glslang::EOpSubgroupInverseBallot:
5071 case glslang::EOpSubgroupBallotBitCount:
5072 case glslang::EOpSubgroupBallotInclusiveBitCount:
5073 case glslang::EOpSubgroupBallotExclusiveBitCount:
5074 case glslang::EOpSubgroupBallotFindLSB:
5075 case glslang::EOpSubgroupBallotFindMSB:
5076 case glslang::EOpSubgroupAdd:
5077 case glslang::EOpSubgroupMul:
5078 case glslang::EOpSubgroupMin:
5079 case glslang::EOpSubgroupMax:
5080 case glslang::EOpSubgroupAnd:
5081 case glslang::EOpSubgroupOr:
5082 case glslang::EOpSubgroupXor:
5083 case glslang::EOpSubgroupInclusiveAdd:
5084 case glslang::EOpSubgroupInclusiveMul:
5085 case glslang::EOpSubgroupInclusiveMin:
5086 case glslang::EOpSubgroupInclusiveMax:
5087 case glslang::EOpSubgroupInclusiveAnd:
5088 case glslang::EOpSubgroupInclusiveOr:
5089 case glslang::EOpSubgroupInclusiveXor:
5090 case glslang::EOpSubgroupExclusiveAdd:
5091 case glslang::EOpSubgroupExclusiveMul:
5092 case glslang::EOpSubgroupExclusiveMin:
5093 case glslang::EOpSubgroupExclusiveMax:
5094 case glslang::EOpSubgroupExclusiveAnd:
5095 case glslang::EOpSubgroupExclusiveOr:
5096 case glslang::EOpSubgroupExclusiveXor:
5097 case glslang::EOpSubgroupQuadSwapHorizontal:
5098 case glslang::EOpSubgroupQuadSwapVertical:
5099 case glslang::EOpSubgroupQuadSwapDiagonal: {
5100 std::vector<spv::Id> operands;
5101 operands.push_back(operand);
5102 return createSubgroupOperation(op, typeId, operands, typeProxy);
5103 }
Rex Xu9d93a232016-05-05 12:30:44 +08005104#ifdef AMD_EXTENSIONS
5105 case glslang::EOpMbcnt:
5106 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5107 libCall = spv::MbcntAMD;
5108 break;
5109
5110 case glslang::EOpCubeFaceIndex:
5111 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5112 libCall = spv::CubeFaceIndexAMD;
5113 break;
5114
5115 case glslang::EOpCubeFaceCoord:
5116 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5117 libCall = spv::CubeFaceCoordAMD;
5118 break;
5119#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005120#ifdef NV_EXTENSIONS
5121 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005122 unaryOp = spv::OpGroupNonUniformPartitionNV;
5123 break;
5124#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005125 default:
5126 return 0;
5127 }
5128
5129 spv::Id id;
5130 if (libCall >= 0) {
5131 std::vector<spv::Id> args;
5132 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005133 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005134 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005135 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005136 }
John Kessenich140f3df2015-06-26 16:58:36 -06005137
John Kessenichead86222018-03-28 18:01:20 -06005138 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005139 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005140 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005141}
5142
John Kessenich7a53f762016-01-20 11:19:27 -07005143// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005144spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5145 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005146{
5147 // Handle unary operations vector by vector.
5148 // The result type is the same type as the original type.
5149 // The algorithm is to:
5150 // - break the matrix into vectors
5151 // - apply the operation to each vector
5152 // - make a matrix out the vector results
5153
5154 // get the types sorted out
5155 int numCols = builder.getNumColumns(operand);
5156 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005157 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5158 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005159 std::vector<spv::Id> results;
5160
5161 // do each vector op
5162 for (int c = 0; c < numCols; ++c) {
5163 std::vector<unsigned int> indexes;
5164 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005165 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5166 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005167 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005168 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005169 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005170 }
5171
5172 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005173 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005174 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005175 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005176}
5177
John Kessenichad7645f2018-06-04 19:11:25 -06005178// For converting integers where both the bitwidth and the signedness could
5179// change, but only do the width change here. The caller is still responsible
5180// for the signedness conversion.
5181spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005182{
John Kessenichad7645f2018-06-04 19:11:25 -06005183 // Get the result type width, based on the type to convert to.
5184 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005185 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005186 case glslang::EOpConvInt16ToUint8:
5187 case glslang::EOpConvIntToUint8:
5188 case glslang::EOpConvInt64ToUint8:
5189 case glslang::EOpConvUint16ToInt8:
5190 case glslang::EOpConvUintToInt8:
5191 case glslang::EOpConvUint64ToInt8:
5192 width = 8;
5193 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005194 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005195 case glslang::EOpConvIntToUint16:
5196 case glslang::EOpConvInt64ToUint16:
5197 case glslang::EOpConvUint8ToInt16:
5198 case glslang::EOpConvUintToInt16:
5199 case glslang::EOpConvUint64ToInt16:
5200 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005201 break;
5202 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005203 case glslang::EOpConvInt16ToUint:
5204 case glslang::EOpConvInt64ToUint:
5205 case glslang::EOpConvUint8ToInt:
5206 case glslang::EOpConvUint16ToInt:
5207 case glslang::EOpConvUint64ToInt:
5208 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005209 break;
5210 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005211 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005212 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005213 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005214 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005215 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005216 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005217 break;
5218
5219 default:
5220 assert(false && "Default missing");
5221 break;
5222 }
5223
John Kessenichad7645f2018-06-04 19:11:25 -06005224 // Get the conversion operation and result type,
5225 // based on the target width, but the source type.
5226 spv::Id type = spv::NoType;
5227 spv::Op convOp = spv::OpNop;
5228 switch(op) {
5229 case glslang::EOpConvInt8ToUint16:
5230 case glslang::EOpConvInt8ToUint:
5231 case glslang::EOpConvInt8ToUint64:
5232 case glslang::EOpConvInt16ToUint8:
5233 case glslang::EOpConvInt16ToUint:
5234 case glslang::EOpConvInt16ToUint64:
5235 case glslang::EOpConvIntToUint8:
5236 case glslang::EOpConvIntToUint16:
5237 case glslang::EOpConvIntToUint64:
5238 case glslang::EOpConvInt64ToUint8:
5239 case glslang::EOpConvInt64ToUint16:
5240 case glslang::EOpConvInt64ToUint:
5241 convOp = spv::OpSConvert;
5242 type = builder.makeIntType(width);
5243 break;
5244 default:
5245 convOp = spv::OpUConvert;
5246 type = builder.makeUintType(width);
5247 break;
5248 }
5249
John Kessenich66011cb2018-03-06 16:12:04 -07005250 if (vectorSize > 0)
5251 type = builder.makeVectorType(type, vectorSize);
5252
John Kessenichad7645f2018-06-04 19:11:25 -06005253 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005254}
5255
John Kessenichead86222018-03-28 18:01:20 -06005256spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5257 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005258{
5259 spv::Op convOp = spv::OpNop;
5260 spv::Id zero = 0;
5261 spv::Id one = 0;
5262
5263 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5264
5265 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005266 case glslang::EOpConvInt8ToBool:
5267 case glslang::EOpConvUint8ToBool:
5268 zero = builder.makeUint8Constant(0);
5269 zero = makeSmearedConstant(zero, vectorSize);
5270 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005271 case glslang::EOpConvInt16ToBool:
5272 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005273 zero = builder.makeUint16Constant(0);
5274 zero = makeSmearedConstant(zero, vectorSize);
5275 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5276 case glslang::EOpConvIntToBool:
5277 case glslang::EOpConvUintToBool:
5278 zero = builder.makeUintConstant(0);
5279 zero = makeSmearedConstant(zero, vectorSize);
5280 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5281 case glslang::EOpConvInt64ToBool:
5282 case glslang::EOpConvUint64ToBool:
5283 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005284 zero = makeSmearedConstant(zero, vectorSize);
5285 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5286
5287 case glslang::EOpConvFloatToBool:
5288 zero = builder.makeFloatConstant(0.0F);
5289 zero = makeSmearedConstant(zero, vectorSize);
5290 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5291
5292 case glslang::EOpConvDoubleToBool:
5293 zero = builder.makeDoubleConstant(0.0);
5294 zero = makeSmearedConstant(zero, vectorSize);
5295 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5296
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005297 case glslang::EOpConvFloat16ToBool:
5298 zero = builder.makeFloat16Constant(0.0F);
5299 zero = makeSmearedConstant(zero, vectorSize);
5300 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005301
John Kessenich140f3df2015-06-26 16:58:36 -06005302 case glslang::EOpConvBoolToFloat:
5303 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005304 zero = builder.makeFloatConstant(0.0F);
5305 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005306 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005307
John Kessenich140f3df2015-06-26 16:58:36 -06005308 case glslang::EOpConvBoolToDouble:
5309 convOp = spv::OpSelect;
5310 zero = builder.makeDoubleConstant(0.0);
5311 one = builder.makeDoubleConstant(1.0);
5312 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005313
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005314 case glslang::EOpConvBoolToFloat16:
5315 convOp = spv::OpSelect;
5316 zero = builder.makeFloat16Constant(0.0F);
5317 one = builder.makeFloat16Constant(1.0F);
5318 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005319
5320 case glslang::EOpConvBoolToInt8:
5321 zero = builder.makeInt8Constant(0);
5322 one = builder.makeInt8Constant(1);
5323 convOp = spv::OpSelect;
5324 break;
5325
5326 case glslang::EOpConvBoolToUint8:
5327 zero = builder.makeUint8Constant(0);
5328 one = builder.makeUint8Constant(1);
5329 convOp = spv::OpSelect;
5330 break;
5331
5332 case glslang::EOpConvBoolToInt16:
5333 zero = builder.makeInt16Constant(0);
5334 one = builder.makeInt16Constant(1);
5335 convOp = spv::OpSelect;
5336 break;
5337
5338 case glslang::EOpConvBoolToUint16:
5339 zero = builder.makeUint16Constant(0);
5340 one = builder.makeUint16Constant(1);
5341 convOp = spv::OpSelect;
5342 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005343
John Kessenich140f3df2015-06-26 16:58:36 -06005344 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005345 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005346 if (op == glslang::EOpConvBoolToInt64)
5347 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005348 else
5349 zero = builder.makeIntConstant(0);
5350
5351 if (op == glslang::EOpConvBoolToInt64)
5352 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005353 else
5354 one = builder.makeIntConstant(1);
5355
John Kessenich140f3df2015-06-26 16:58:36 -06005356 convOp = spv::OpSelect;
5357 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005358
John Kessenich140f3df2015-06-26 16:58:36 -06005359 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005360 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005361 if (op == glslang::EOpConvBoolToUint64)
5362 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005363 else
5364 zero = builder.makeUintConstant(0);
5365
5366 if (op == glslang::EOpConvBoolToUint64)
5367 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005368 else
5369 one = builder.makeUintConstant(1);
5370
John Kessenich140f3df2015-06-26 16:58:36 -06005371 convOp = spv::OpSelect;
5372 break;
5373
John Kessenich66011cb2018-03-06 16:12:04 -07005374 case glslang::EOpConvInt8ToFloat16:
5375 case glslang::EOpConvInt8ToFloat:
5376 case glslang::EOpConvInt8ToDouble:
5377 case glslang::EOpConvInt16ToFloat16:
5378 case glslang::EOpConvInt16ToFloat:
5379 case glslang::EOpConvInt16ToDouble:
5380 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005381 case glslang::EOpConvIntToFloat:
5382 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005383 case glslang::EOpConvInt64ToFloat:
5384 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005385 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005386 convOp = spv::OpConvertSToF;
5387 break;
5388
John Kessenich66011cb2018-03-06 16:12:04 -07005389 case glslang::EOpConvUint8ToFloat16:
5390 case glslang::EOpConvUint8ToFloat:
5391 case glslang::EOpConvUint8ToDouble:
5392 case glslang::EOpConvUint16ToFloat16:
5393 case glslang::EOpConvUint16ToFloat:
5394 case glslang::EOpConvUint16ToDouble:
5395 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005396 case glslang::EOpConvUintToFloat:
5397 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005398 case glslang::EOpConvUint64ToFloat:
5399 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005400 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005401 convOp = spv::OpConvertUToF;
5402 break;
5403
5404 case glslang::EOpConvDoubleToFloat:
5405 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005406 case glslang::EOpConvDoubleToFloat16:
5407 case glslang::EOpConvFloat16ToDouble:
5408 case glslang::EOpConvFloatToFloat16:
5409 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005410 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005411 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005412 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005413 break;
5414
John Kessenich66011cb2018-03-06 16:12:04 -07005415 case glslang::EOpConvFloat16ToInt8:
5416 case glslang::EOpConvFloatToInt8:
5417 case glslang::EOpConvDoubleToInt8:
5418 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005419 case glslang::EOpConvFloatToInt16:
5420 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005421 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005422 case glslang::EOpConvFloatToInt:
5423 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005424 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005425 case glslang::EOpConvFloatToInt64:
5426 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005427 convOp = spv::OpConvertFToS;
5428 break;
5429
John Kessenich66011cb2018-03-06 16:12:04 -07005430 case glslang::EOpConvUint8ToInt8:
5431 case glslang::EOpConvInt8ToUint8:
5432 case glslang::EOpConvUint16ToInt16:
5433 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005434 case glslang::EOpConvUintToInt:
5435 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005436 case glslang::EOpConvUint64ToInt64:
5437 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005438 if (builder.isInSpecConstCodeGenMode()) {
5439 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005440 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5441 zero = builder.makeUint8Constant(0);
5442 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005443 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005444 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5445 zero = builder.makeUint64Constant(0);
5446 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005447 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005448 }
qining189b2032016-04-12 23:16:20 -04005449 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005450 // Use OpIAdd, instead of OpBitcast to do the conversion when
5451 // generating for OpSpecConstantOp instruction.
5452 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5453 }
5454 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005455 convOp = spv::OpBitcast;
5456 break;
5457
John Kessenich66011cb2018-03-06 16:12:04 -07005458 case glslang::EOpConvFloat16ToUint8:
5459 case glslang::EOpConvFloatToUint8:
5460 case glslang::EOpConvDoubleToUint8:
5461 case glslang::EOpConvFloat16ToUint16:
5462 case glslang::EOpConvFloatToUint16:
5463 case glslang::EOpConvDoubleToUint16:
5464 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005465 case glslang::EOpConvFloatToUint:
5466 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005467 case glslang::EOpConvFloatToUint64:
5468 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005469 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005470 convOp = spv::OpConvertFToU;
5471 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005472
John Kessenich66011cb2018-03-06 16:12:04 -07005473 case glslang::EOpConvInt8ToInt16:
5474 case glslang::EOpConvInt8ToInt:
5475 case glslang::EOpConvInt8ToInt64:
5476 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005477 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005478 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005479 case glslang::EOpConvIntToInt8:
5480 case glslang::EOpConvIntToInt16:
5481 case glslang::EOpConvIntToInt64:
5482 case glslang::EOpConvInt64ToInt8:
5483 case glslang::EOpConvInt64ToInt16:
5484 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005485 convOp = spv::OpSConvert;
5486 break;
5487
John Kessenich66011cb2018-03-06 16:12:04 -07005488 case glslang::EOpConvUint8ToUint16:
5489 case glslang::EOpConvUint8ToUint:
5490 case glslang::EOpConvUint8ToUint64:
5491 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005492 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005493 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005494 case glslang::EOpConvUintToUint8:
5495 case glslang::EOpConvUintToUint16:
5496 case glslang::EOpConvUintToUint64:
5497 case glslang::EOpConvUint64ToUint8:
5498 case glslang::EOpConvUint64ToUint16:
5499 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005500 convOp = spv::OpUConvert;
5501 break;
5502
John Kessenich66011cb2018-03-06 16:12:04 -07005503 case glslang::EOpConvInt8ToUint16:
5504 case glslang::EOpConvInt8ToUint:
5505 case glslang::EOpConvInt8ToUint64:
5506 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005507 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005508 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005509 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005510 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005511 case glslang::EOpConvIntToUint64:
5512 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005513 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005514 case glslang::EOpConvInt64ToUint:
5515 case glslang::EOpConvUint8ToInt16:
5516 case glslang::EOpConvUint8ToInt:
5517 case glslang::EOpConvUint8ToInt64:
5518 case glslang::EOpConvUint16ToInt8:
5519 case glslang::EOpConvUint16ToInt:
5520 case glslang::EOpConvUint16ToInt64:
5521 case glslang::EOpConvUintToInt8:
5522 case glslang::EOpConvUintToInt16:
5523 case glslang::EOpConvUintToInt64:
5524 case glslang::EOpConvUint64ToInt8:
5525 case glslang::EOpConvUint64ToInt16:
5526 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005527 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005528 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005529
5530 if (builder.isInSpecConstCodeGenMode()) {
5531 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005532 switch(op) {
5533 case glslang::EOpConvInt16ToUint8:
5534 case glslang::EOpConvIntToUint8:
5535 case glslang::EOpConvInt64ToUint8:
5536 case glslang::EOpConvUint16ToInt8:
5537 case glslang::EOpConvUintToInt8:
5538 case glslang::EOpConvUint64ToInt8:
5539 zero = builder.makeUint8Constant(0);
5540 break;
5541 case glslang::EOpConvInt8ToUint16:
5542 case glslang::EOpConvIntToUint16:
5543 case glslang::EOpConvInt64ToUint16:
5544 case glslang::EOpConvUint8ToInt16:
5545 case glslang::EOpConvUintToInt16:
5546 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005547 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005548 break;
5549 case glslang::EOpConvInt8ToUint:
5550 case glslang::EOpConvInt16ToUint:
5551 case glslang::EOpConvInt64ToUint:
5552 case glslang::EOpConvUint8ToInt:
5553 case glslang::EOpConvUint16ToInt:
5554 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005555 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005556 break;
5557 case glslang::EOpConvInt8ToUint64:
5558 case glslang::EOpConvInt16ToUint64:
5559 case glslang::EOpConvIntToUint64:
5560 case glslang::EOpConvUint8ToInt64:
5561 case glslang::EOpConvUint16ToInt64:
5562 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005563 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005564 break;
5565 default:
5566 assert(false && "Default missing");
5567 break;
5568 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005569 zero = makeSmearedConstant(zero, vectorSize);
5570 // Use OpIAdd, instead of OpBitcast to do the conversion when
5571 // generating for OpSpecConstantOp instruction.
5572 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5573 }
5574 // For normal run-time conversion instruction, use OpBitcast.
5575 convOp = spv::OpBitcast;
5576 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005577 default:
5578 break;
5579 }
5580
5581 spv::Id result = 0;
5582 if (convOp == spv::OpNop)
5583 return result;
5584
5585 if (convOp == spv::OpSelect) {
5586 zero = makeSmearedConstant(zero, vectorSize);
5587 one = makeSmearedConstant(one, vectorSize);
5588 result = builder.createTriOp(convOp, destType, operand, one, zero);
5589 } else
5590 result = builder.createUnaryOp(convOp, destType, operand);
5591
John Kessenichead86222018-03-28 18:01:20 -06005592 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005593 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005594 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005595}
5596
5597spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5598{
5599 if (vectorSize == 0)
5600 return constant;
5601
5602 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5603 std::vector<spv::Id> components;
5604 for (int c = 0; c < vectorSize; ++c)
5605 components.push_back(constant);
5606 return builder.makeCompositeConstant(vectorTypeId, components);
5607}
5608
John Kessenich426394d2015-07-23 10:22:48 -06005609// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005610spv::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 -06005611{
5612 spv::Op opCode = spv::OpNop;
5613
5614 switch (op) {
5615 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005616 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005617 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005618 opCode = spv::OpAtomicIAdd;
5619 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005620 case glslang::EOpAtomicCounterSubtract:
5621 opCode = spv::OpAtomicISub;
5622 break;
John Kessenich426394d2015-07-23 10:22:48 -06005623 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005624 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005625 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005626 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005627 break;
5628 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005629 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005630 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005631 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005632 break;
5633 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005634 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005635 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005636 opCode = spv::OpAtomicAnd;
5637 break;
5638 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005639 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005640 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005641 opCode = spv::OpAtomicOr;
5642 break;
5643 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005644 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005645 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005646 opCode = spv::OpAtomicXor;
5647 break;
5648 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005649 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005650 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005651 opCode = spv::OpAtomicExchange;
5652 break;
5653 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005654 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005655 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005656 opCode = spv::OpAtomicCompareExchange;
5657 break;
5658 case glslang::EOpAtomicCounterIncrement:
5659 opCode = spv::OpAtomicIIncrement;
5660 break;
5661 case glslang::EOpAtomicCounterDecrement:
5662 opCode = spv::OpAtomicIDecrement;
5663 break;
5664 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005665 case glslang::EOpImageAtomicLoad:
5666 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005667 opCode = spv::OpAtomicLoad;
5668 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005669 case glslang::EOpAtomicStore:
5670 case glslang::EOpImageAtomicStore:
5671 opCode = spv::OpAtomicStore;
5672 break;
John Kessenich426394d2015-07-23 10:22:48 -06005673 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005674 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005675 break;
5676 }
5677
Rex Xue8fe8b02017-09-26 15:42:56 +08005678 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5679 builder.addCapability(spv::CapabilityInt64Atomics);
5680
John Kessenich426394d2015-07-23 10:22:48 -06005681 // Sort out the operands
5682 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005683 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005684 // - compare-exchange swaps the value and comparator
5685 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005686 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005687 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5688 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5689 spv::Id scopeId;
5690 if (glslangIntermediate->usingVulkanMemoryModel()) {
5691 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5692 } else {
5693 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5694 }
5695 // semantics default to relaxed
5696 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5697 spv::Id semanticsId2 = semanticsId;
5698
5699 pointerId = operands[0];
5700 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5701 // no additional operands
5702 } else if (opCode == spv::OpAtomicCompareExchange) {
5703 compareId = operands[1];
5704 valueId = operands[2];
5705 if (operands.size() > 3) {
5706 scopeId = operands[3];
5707 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5708 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5709 }
5710 } else if (opCode == spv::OpAtomicLoad) {
5711 if (operands.size() > 1) {
5712 scopeId = operands[1];
5713 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5714 }
5715 } else {
5716 // atomic store or RMW
5717 valueId = operands[1];
5718 if (operands.size() > 2) {
5719 scopeId = operands[2];
5720 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5721 }
Rex Xu04db3f52015-09-16 11:44:02 +08005722 }
John Kessenich426394d2015-07-23 10:22:48 -06005723
Jeff Bolz36831c92018-09-05 10:11:41 -05005724 // Check for capabilities
5725 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5726 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5727 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5728 }
John Kessenich426394d2015-07-23 10:22:48 -06005729
Jeff Bolz36831c92018-09-05 10:11:41 -05005730 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5731 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5732 }
John Kessenich48d6e792017-10-06 21:21:48 -06005733
Jeff Bolz36831c92018-09-05 10:11:41 -05005734 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5735 spvAtomicOperands.push_back(pointerId);
5736 spvAtomicOperands.push_back(scopeId);
5737 spvAtomicOperands.push_back(semanticsId);
5738 if (opCode == spv::OpAtomicCompareExchange) {
5739 spvAtomicOperands.push_back(semanticsId2);
5740 spvAtomicOperands.push_back(valueId);
5741 spvAtomicOperands.push_back(compareId);
5742 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5743 spvAtomicOperands.push_back(valueId);
5744 }
John Kessenich48d6e792017-10-06 21:21:48 -06005745
Jeff Bolz36831c92018-09-05 10:11:41 -05005746 if (opCode == spv::OpAtomicStore) {
5747 builder.createNoResultOp(opCode, spvAtomicOperands);
5748 return 0;
5749 } else {
5750 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5751
5752 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5753 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5754 if (op == glslang::EOpAtomicCounterDecrement)
5755 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5756
5757 return resultId;
5758 }
John Kessenich426394d2015-07-23 10:22:48 -06005759}
5760
John Kessenich91cef522016-05-05 16:45:40 -06005761// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005762spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005763{
Corentin Walleze7061422018-08-08 15:20:15 +02005764#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005765 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5766 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005767#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005768
Rex Xu51596642016-09-21 18:56:12 +08005769 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005770 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005771 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5772
chaocf200da82016-12-20 12:44:35 -08005773 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5774 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005775 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5776 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005777 } else if (op == glslang::EOpAnyInvocation ||
5778 op == glslang::EOpAllInvocations ||
5779 op == glslang::EOpAllInvocationsEqual) {
5780 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5781 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005782 } else {
5783 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005784#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005785 if (op == glslang::EOpMinInvocationsNonUniform ||
5786 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005787 op == glslang::EOpAddInvocationsNonUniform ||
5788 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5789 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5790 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5791 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5792 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5793 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005794 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005795#endif
Rex Xu51596642016-09-21 18:56:12 +08005796
Rex Xu9d93a232016-05-05 12:30:44 +08005797#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005798 switch (op) {
5799 case glslang::EOpMinInvocations:
5800 case glslang::EOpMaxInvocations:
5801 case glslang::EOpAddInvocations:
5802 case glslang::EOpMinInvocationsNonUniform:
5803 case glslang::EOpMaxInvocationsNonUniform:
5804 case glslang::EOpAddInvocationsNonUniform:
5805 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005806 break;
5807 case glslang::EOpMinInvocationsInclusiveScan:
5808 case glslang::EOpMaxInvocationsInclusiveScan:
5809 case glslang::EOpAddInvocationsInclusiveScan:
5810 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5811 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5812 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5813 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005814 break;
5815 case glslang::EOpMinInvocationsExclusiveScan:
5816 case glslang::EOpMaxInvocationsExclusiveScan:
5817 case glslang::EOpAddInvocationsExclusiveScan:
5818 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5819 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5820 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5821 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005822 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005823 default:
5824 break;
Rex Xu430ef402016-10-14 17:22:23 +08005825 }
John Kessenich149afc32018-08-14 13:31:43 -06005826 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5827 spvGroupOperands.push_back(scope);
5828 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005829 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005830 spvGroupOperands.push_back(groupOp);
5831 }
Rex Xu9d93a232016-05-05 12:30:44 +08005832#endif
Rex Xu51596642016-09-21 18:56:12 +08005833 }
5834
John Kessenich149afc32018-08-14 13:31:43 -06005835 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5836 spv::IdImmediate op = { true, *opIt };
5837 spvGroupOperands.push_back(op);
5838 }
John Kessenich91cef522016-05-05 16:45:40 -06005839
5840 switch (op) {
5841 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005842 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005843 break;
John Kessenich91cef522016-05-05 16:45:40 -06005844 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005845 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005846 break;
John Kessenich91cef522016-05-05 16:45:40 -06005847 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005848 opCode = spv::OpSubgroupAllEqualKHR;
5849 break;
Rex Xu51596642016-09-21 18:56:12 +08005850 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005851 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005852 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005853 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005854 break;
5855 case glslang::EOpReadFirstInvocation:
5856 opCode = spv::OpSubgroupFirstInvocationKHR;
5857 break;
5858 case glslang::EOpBallot:
5859 {
5860 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5861 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5862 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5863 //
5864 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5865 //
5866 spv::Id uintType = builder.makeUintType(32);
5867 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5868 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5869
5870 std::vector<spv::Id> components;
5871 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5872 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5873
5874 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5875 return builder.createUnaryOp(spv::OpBitcast, typeId,
5876 builder.createCompositeConstruct(uvec2Type, components));
5877 }
5878
Rex Xu9d93a232016-05-05 12:30:44 +08005879#ifdef AMD_EXTENSIONS
5880 case glslang::EOpMinInvocations:
5881 case glslang::EOpMaxInvocations:
5882 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005883 case glslang::EOpMinInvocationsInclusiveScan:
5884 case glslang::EOpMaxInvocationsInclusiveScan:
5885 case glslang::EOpAddInvocationsInclusiveScan:
5886 case glslang::EOpMinInvocationsExclusiveScan:
5887 case glslang::EOpMaxInvocationsExclusiveScan:
5888 case glslang::EOpAddInvocationsExclusiveScan:
5889 if (op == glslang::EOpMinInvocations ||
5890 op == glslang::EOpMinInvocationsInclusiveScan ||
5891 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005892 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005893 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005894 else {
5895 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005896 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005897 else
Rex Xu51596642016-09-21 18:56:12 +08005898 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005899 }
Rex Xu430ef402016-10-14 17:22:23 +08005900 } else if (op == glslang::EOpMaxInvocations ||
5901 op == glslang::EOpMaxInvocationsInclusiveScan ||
5902 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005903 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005904 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005905 else {
5906 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005907 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005908 else
Rex Xu51596642016-09-21 18:56:12 +08005909 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005910 }
5911 } else {
5912 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005913 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005914 else
Rex Xu51596642016-09-21 18:56:12 +08005915 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005916 }
5917
Rex Xu2bbbe062016-08-23 15:41:05 +08005918 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005919 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005920
5921 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005922 case glslang::EOpMinInvocationsNonUniform:
5923 case glslang::EOpMaxInvocationsNonUniform:
5924 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005925 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5926 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5927 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5928 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5929 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5930 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5931 if (op == glslang::EOpMinInvocationsNonUniform ||
5932 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5933 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005934 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005935 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005936 else {
5937 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005938 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005939 else
Rex Xu51596642016-09-21 18:56:12 +08005940 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005941 }
5942 }
Rex Xu430ef402016-10-14 17:22:23 +08005943 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5944 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5945 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005946 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005947 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005948 else {
5949 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005950 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005951 else
Rex Xu51596642016-09-21 18:56:12 +08005952 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005953 }
5954 }
5955 else {
5956 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005957 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005958 else
Rex Xu51596642016-09-21 18:56:12 +08005959 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005960 }
5961
Rex Xu2bbbe062016-08-23 15:41:05 +08005962 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005963 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005964
5965 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005966#endif
John Kessenich91cef522016-05-05 16:45:40 -06005967 default:
5968 logger->missingFunctionality("invocation operation");
5969 return spv::NoResult;
5970 }
Rex Xu51596642016-09-21 18:56:12 +08005971
5972 assert(opCode != spv::OpNop);
5973 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005974}
5975
Rex Xu2bbbe062016-08-23 15:41:05 +08005976// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005977spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5978 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005979{
Rex Xub7072052016-09-26 15:53:40 +08005980#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005981 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5982 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005983 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005984 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005985 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5986 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5987 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005988#else
5989 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5990 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005991 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5992 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005993#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005994
5995 // Handle group invocation operations scalar by scalar.
5996 // The result type is the same type as the original type.
5997 // The algorithm is to:
5998 // - break the vector into scalars
5999 // - apply the operation to each scalar
6000 // - make a vector out the scalar results
6001
6002 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006003 int numComponents = builder.getNumComponents(operands[0]);
6004 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006005 std::vector<spv::Id> results;
6006
6007 // do each scalar op
6008 for (int comp = 0; comp < numComponents; ++comp) {
6009 std::vector<unsigned int> indexes;
6010 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006011 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6012 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006013 if (op == spv::OpSubgroupReadInvocationKHR) {
6014 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006015 spv::IdImmediate operand = { true, operands[1] };
6016 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006017 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006018 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6019 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006020 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006021 spv::IdImmediate operand = { true, operands[1] };
6022 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006023 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006024 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6025 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006026 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006027 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006028 spvGroupOperands.push_back(scalar);
6029 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006030
Rex Xub7072052016-09-26 15:53:40 +08006031 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006032 }
6033
6034 // put the pieces together
6035 return builder.createCompositeConstruct(typeId, results);
6036}
Rex Xu2bbbe062016-08-23 15:41:05 +08006037
John Kessenich66011cb2018-03-06 16:12:04 -07006038// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006039spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6040 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006041{
6042 // Add the required capabilities.
6043 switch (op) {
6044 case glslang::EOpSubgroupElect:
6045 builder.addCapability(spv::CapabilityGroupNonUniform);
6046 break;
6047 case glslang::EOpSubgroupAll:
6048 case glslang::EOpSubgroupAny:
6049 case glslang::EOpSubgroupAllEqual:
6050 builder.addCapability(spv::CapabilityGroupNonUniform);
6051 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6052 break;
6053 case glslang::EOpSubgroupBroadcast:
6054 case glslang::EOpSubgroupBroadcastFirst:
6055 case glslang::EOpSubgroupBallot:
6056 case glslang::EOpSubgroupInverseBallot:
6057 case glslang::EOpSubgroupBallotBitExtract:
6058 case glslang::EOpSubgroupBallotBitCount:
6059 case glslang::EOpSubgroupBallotInclusiveBitCount:
6060 case glslang::EOpSubgroupBallotExclusiveBitCount:
6061 case glslang::EOpSubgroupBallotFindLSB:
6062 case glslang::EOpSubgroupBallotFindMSB:
6063 builder.addCapability(spv::CapabilityGroupNonUniform);
6064 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6065 break;
6066 case glslang::EOpSubgroupShuffle:
6067 case glslang::EOpSubgroupShuffleXor:
6068 builder.addCapability(spv::CapabilityGroupNonUniform);
6069 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6070 break;
6071 case glslang::EOpSubgroupShuffleUp:
6072 case glslang::EOpSubgroupShuffleDown:
6073 builder.addCapability(spv::CapabilityGroupNonUniform);
6074 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6075 break;
6076 case glslang::EOpSubgroupAdd:
6077 case glslang::EOpSubgroupMul:
6078 case glslang::EOpSubgroupMin:
6079 case glslang::EOpSubgroupMax:
6080 case glslang::EOpSubgroupAnd:
6081 case glslang::EOpSubgroupOr:
6082 case glslang::EOpSubgroupXor:
6083 case glslang::EOpSubgroupInclusiveAdd:
6084 case glslang::EOpSubgroupInclusiveMul:
6085 case glslang::EOpSubgroupInclusiveMin:
6086 case glslang::EOpSubgroupInclusiveMax:
6087 case glslang::EOpSubgroupInclusiveAnd:
6088 case glslang::EOpSubgroupInclusiveOr:
6089 case glslang::EOpSubgroupInclusiveXor:
6090 case glslang::EOpSubgroupExclusiveAdd:
6091 case glslang::EOpSubgroupExclusiveMul:
6092 case glslang::EOpSubgroupExclusiveMin:
6093 case glslang::EOpSubgroupExclusiveMax:
6094 case glslang::EOpSubgroupExclusiveAnd:
6095 case glslang::EOpSubgroupExclusiveOr:
6096 case glslang::EOpSubgroupExclusiveXor:
6097 builder.addCapability(spv::CapabilityGroupNonUniform);
6098 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6099 break;
6100 case glslang::EOpSubgroupClusteredAdd:
6101 case glslang::EOpSubgroupClusteredMul:
6102 case glslang::EOpSubgroupClusteredMin:
6103 case glslang::EOpSubgroupClusteredMax:
6104 case glslang::EOpSubgroupClusteredAnd:
6105 case glslang::EOpSubgroupClusteredOr:
6106 case glslang::EOpSubgroupClusteredXor:
6107 builder.addCapability(spv::CapabilityGroupNonUniform);
6108 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6109 break;
6110 case glslang::EOpSubgroupQuadBroadcast:
6111 case glslang::EOpSubgroupQuadSwapHorizontal:
6112 case glslang::EOpSubgroupQuadSwapVertical:
6113 case glslang::EOpSubgroupQuadSwapDiagonal:
6114 builder.addCapability(spv::CapabilityGroupNonUniform);
6115 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6116 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006117#ifdef NV_EXTENSIONS
6118 case glslang::EOpSubgroupPartitionedAdd:
6119 case glslang::EOpSubgroupPartitionedMul:
6120 case glslang::EOpSubgroupPartitionedMin:
6121 case glslang::EOpSubgroupPartitionedMax:
6122 case glslang::EOpSubgroupPartitionedAnd:
6123 case glslang::EOpSubgroupPartitionedOr:
6124 case glslang::EOpSubgroupPartitionedXor:
6125 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6126 case glslang::EOpSubgroupPartitionedInclusiveMul:
6127 case glslang::EOpSubgroupPartitionedInclusiveMin:
6128 case glslang::EOpSubgroupPartitionedInclusiveMax:
6129 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6130 case glslang::EOpSubgroupPartitionedInclusiveOr:
6131 case glslang::EOpSubgroupPartitionedInclusiveXor:
6132 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6133 case glslang::EOpSubgroupPartitionedExclusiveMul:
6134 case glslang::EOpSubgroupPartitionedExclusiveMin:
6135 case glslang::EOpSubgroupPartitionedExclusiveMax:
6136 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6137 case glslang::EOpSubgroupPartitionedExclusiveOr:
6138 case glslang::EOpSubgroupPartitionedExclusiveXor:
6139 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6140 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6141 break;
6142#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006143 default: assert(0 && "Unhandled subgroup operation!");
6144 }
6145
6146 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6147 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6148 const bool isBool = typeProxy == glslang::EbtBool;
6149
6150 spv::Op opCode = spv::OpNop;
6151
6152 // Figure out which opcode to use.
6153 switch (op) {
6154 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6155 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6156 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6157 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6158 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6159 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6160 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6161 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6162 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6163 case glslang::EOpSubgroupBallotBitCount:
6164 case glslang::EOpSubgroupBallotInclusiveBitCount:
6165 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6166 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6167 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6168 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6169 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6170 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6171 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6172 case glslang::EOpSubgroupAdd:
6173 case glslang::EOpSubgroupInclusiveAdd:
6174 case glslang::EOpSubgroupExclusiveAdd:
6175 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006176#ifdef NV_EXTENSIONS
6177 case glslang::EOpSubgroupPartitionedAdd:
6178 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6179 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6180#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006181 if (isFloat) {
6182 opCode = spv::OpGroupNonUniformFAdd;
6183 } else {
6184 opCode = spv::OpGroupNonUniformIAdd;
6185 }
6186 break;
6187 case glslang::EOpSubgroupMul:
6188 case glslang::EOpSubgroupInclusiveMul:
6189 case glslang::EOpSubgroupExclusiveMul:
6190 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006191#ifdef NV_EXTENSIONS
6192 case glslang::EOpSubgroupPartitionedMul:
6193 case glslang::EOpSubgroupPartitionedInclusiveMul:
6194 case glslang::EOpSubgroupPartitionedExclusiveMul:
6195#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006196 if (isFloat) {
6197 opCode = spv::OpGroupNonUniformFMul;
6198 } else {
6199 opCode = spv::OpGroupNonUniformIMul;
6200 }
6201 break;
6202 case glslang::EOpSubgroupMin:
6203 case glslang::EOpSubgroupInclusiveMin:
6204 case glslang::EOpSubgroupExclusiveMin:
6205 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006206#ifdef NV_EXTENSIONS
6207 case glslang::EOpSubgroupPartitionedMin:
6208 case glslang::EOpSubgroupPartitionedInclusiveMin:
6209 case glslang::EOpSubgroupPartitionedExclusiveMin:
6210#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006211 if (isFloat) {
6212 opCode = spv::OpGroupNonUniformFMin;
6213 } else if (isUnsigned) {
6214 opCode = spv::OpGroupNonUniformUMin;
6215 } else {
6216 opCode = spv::OpGroupNonUniformSMin;
6217 }
6218 break;
6219 case glslang::EOpSubgroupMax:
6220 case glslang::EOpSubgroupInclusiveMax:
6221 case glslang::EOpSubgroupExclusiveMax:
6222 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006223#ifdef NV_EXTENSIONS
6224 case glslang::EOpSubgroupPartitionedMax:
6225 case glslang::EOpSubgroupPartitionedInclusiveMax:
6226 case glslang::EOpSubgroupPartitionedExclusiveMax:
6227#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006228 if (isFloat) {
6229 opCode = spv::OpGroupNonUniformFMax;
6230 } else if (isUnsigned) {
6231 opCode = spv::OpGroupNonUniformUMax;
6232 } else {
6233 opCode = spv::OpGroupNonUniformSMax;
6234 }
6235 break;
6236 case glslang::EOpSubgroupAnd:
6237 case glslang::EOpSubgroupInclusiveAnd:
6238 case glslang::EOpSubgroupExclusiveAnd:
6239 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006240#ifdef NV_EXTENSIONS
6241 case glslang::EOpSubgroupPartitionedAnd:
6242 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6243 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6244#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006245 if (isBool) {
6246 opCode = spv::OpGroupNonUniformLogicalAnd;
6247 } else {
6248 opCode = spv::OpGroupNonUniformBitwiseAnd;
6249 }
6250 break;
6251 case glslang::EOpSubgroupOr:
6252 case glslang::EOpSubgroupInclusiveOr:
6253 case glslang::EOpSubgroupExclusiveOr:
6254 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006255#ifdef NV_EXTENSIONS
6256 case glslang::EOpSubgroupPartitionedOr:
6257 case glslang::EOpSubgroupPartitionedInclusiveOr:
6258 case glslang::EOpSubgroupPartitionedExclusiveOr:
6259#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006260 if (isBool) {
6261 opCode = spv::OpGroupNonUniformLogicalOr;
6262 } else {
6263 opCode = spv::OpGroupNonUniformBitwiseOr;
6264 }
6265 break;
6266 case glslang::EOpSubgroupXor:
6267 case glslang::EOpSubgroupInclusiveXor:
6268 case glslang::EOpSubgroupExclusiveXor:
6269 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006270#ifdef NV_EXTENSIONS
6271 case glslang::EOpSubgroupPartitionedXor:
6272 case glslang::EOpSubgroupPartitionedInclusiveXor:
6273 case glslang::EOpSubgroupPartitionedExclusiveXor:
6274#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006275 if (isBool) {
6276 opCode = spv::OpGroupNonUniformLogicalXor;
6277 } else {
6278 opCode = spv::OpGroupNonUniformBitwiseXor;
6279 }
6280 break;
6281 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6282 case glslang::EOpSubgroupQuadSwapHorizontal:
6283 case glslang::EOpSubgroupQuadSwapVertical:
6284 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6285 default: assert(0 && "Unhandled subgroup operation!");
6286 }
6287
John Kessenich149afc32018-08-14 13:31:43 -06006288 // get the right Group Operation
6289 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006290 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006291 default:
6292 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006293 case glslang::EOpSubgroupBallotBitCount:
6294 case glslang::EOpSubgroupAdd:
6295 case glslang::EOpSubgroupMul:
6296 case glslang::EOpSubgroupMin:
6297 case glslang::EOpSubgroupMax:
6298 case glslang::EOpSubgroupAnd:
6299 case glslang::EOpSubgroupOr:
6300 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006301 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006302 break;
6303 case glslang::EOpSubgroupBallotInclusiveBitCount:
6304 case glslang::EOpSubgroupInclusiveAdd:
6305 case glslang::EOpSubgroupInclusiveMul:
6306 case glslang::EOpSubgroupInclusiveMin:
6307 case glslang::EOpSubgroupInclusiveMax:
6308 case glslang::EOpSubgroupInclusiveAnd:
6309 case glslang::EOpSubgroupInclusiveOr:
6310 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006311 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006312 break;
6313 case glslang::EOpSubgroupBallotExclusiveBitCount:
6314 case glslang::EOpSubgroupExclusiveAdd:
6315 case glslang::EOpSubgroupExclusiveMul:
6316 case glslang::EOpSubgroupExclusiveMin:
6317 case glslang::EOpSubgroupExclusiveMax:
6318 case glslang::EOpSubgroupExclusiveAnd:
6319 case glslang::EOpSubgroupExclusiveOr:
6320 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006321 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006322 break;
6323 case glslang::EOpSubgroupClusteredAdd:
6324 case glslang::EOpSubgroupClusteredMul:
6325 case glslang::EOpSubgroupClusteredMin:
6326 case glslang::EOpSubgroupClusteredMax:
6327 case glslang::EOpSubgroupClusteredAnd:
6328 case glslang::EOpSubgroupClusteredOr:
6329 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006330 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006331 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006332#ifdef NV_EXTENSIONS
6333 case glslang::EOpSubgroupPartitionedAdd:
6334 case glslang::EOpSubgroupPartitionedMul:
6335 case glslang::EOpSubgroupPartitionedMin:
6336 case glslang::EOpSubgroupPartitionedMax:
6337 case glslang::EOpSubgroupPartitionedAnd:
6338 case glslang::EOpSubgroupPartitionedOr:
6339 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006340 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006341 break;
6342 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6343 case glslang::EOpSubgroupPartitionedInclusiveMul:
6344 case glslang::EOpSubgroupPartitionedInclusiveMin:
6345 case glslang::EOpSubgroupPartitionedInclusiveMax:
6346 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6347 case glslang::EOpSubgroupPartitionedInclusiveOr:
6348 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006349 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006350 break;
6351 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6352 case glslang::EOpSubgroupPartitionedExclusiveMul:
6353 case glslang::EOpSubgroupPartitionedExclusiveMin:
6354 case glslang::EOpSubgroupPartitionedExclusiveMax:
6355 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6356 case glslang::EOpSubgroupPartitionedExclusiveOr:
6357 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006358 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006359 break;
6360#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006361 }
6362
John Kessenich149afc32018-08-14 13:31:43 -06006363 // build the instruction
6364 std::vector<spv::IdImmediate> spvGroupOperands;
6365
6366 // Every operation begins with the Execution Scope operand.
6367 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6368 spvGroupOperands.push_back(executionScope);
6369
6370 // Next, for all operations that use a Group Operation, push that as an operand.
6371 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006372 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006373 spvGroupOperands.push_back(groupOperand);
6374 }
6375
John Kessenich66011cb2018-03-06 16:12:04 -07006376 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006377 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6378 spv::IdImmediate operand = { true, *opIt };
6379 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006380 }
6381
6382 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006383 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006384 switch (op) {
6385 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006386 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6387 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6388 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6389 }
6390 if (directionId != spv::NoResult) {
6391 spv::IdImmediate direction = { true, directionId };
6392 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006393 }
6394
6395 return builder.createOp(opCode, typeId, spvGroupOperands);
6396}
6397
John Kessenich5e4b1242015-08-06 22:53:06 -06006398spv::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 -06006399{
John Kessenich66011cb2018-03-06 16:12:04 -07006400 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6401 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006402
John Kessenich140f3df2015-06-26 16:58:36 -06006403 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006404 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006405 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006406 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006407 spv::Id typeId0 = 0;
6408 if (consumedOperands > 0)
6409 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006410 spv::Id typeId1 = 0;
6411 if (consumedOperands > 1)
6412 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006413 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006414
6415 switch (op) {
6416 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006417 if (isFloat)
6418 libCall = spv::GLSLstd450FMin;
6419 else if (isUnsigned)
6420 libCall = spv::GLSLstd450UMin;
6421 else
6422 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006423 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006424 break;
6425 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006426 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006427 break;
6428 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006429 if (isFloat)
6430 libCall = spv::GLSLstd450FMax;
6431 else if (isUnsigned)
6432 libCall = spv::GLSLstd450UMax;
6433 else
6434 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006435 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006436 break;
6437 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006438 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006439 break;
6440 case glslang::EOpDot:
6441 opCode = spv::OpDot;
6442 break;
6443 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006444 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006445 break;
6446
6447 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006448 if (isFloat)
6449 libCall = spv::GLSLstd450FClamp;
6450 else if (isUnsigned)
6451 libCall = spv::GLSLstd450UClamp;
6452 else
6453 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006454 builder.promoteScalar(precision, operands.front(), operands[1]);
6455 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006456 break;
6457 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006458 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6459 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006460 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006461 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006462 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006463 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006464 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006465 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006466 break;
6467 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006468 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006469 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006470 break;
6471 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006472 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006473 builder.promoteScalar(precision, operands[0], operands[2]);
6474 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006475 break;
6476
6477 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006478 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006479 break;
6480 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006481 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006482 break;
6483 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006484 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006485 break;
6486 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006487 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006488 break;
6489 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006490 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006491 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006492 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006493#ifdef AMD_EXTENSIONS
6494 if (typeProxy == glslang::EbtFloat16)
6495 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6496#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006497 libCall = spv::GLSLstd450InterpolateAtSample;
6498 break;
6499 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006500#ifdef AMD_EXTENSIONS
6501 if (typeProxy == glslang::EbtFloat16)
6502 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6503#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006504 libCall = spv::GLSLstd450InterpolateAtOffset;
6505 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006506 case glslang::EOpAddCarry:
6507 opCode = spv::OpIAddCarry;
6508 typeId = builder.makeStructResultType(typeId0, typeId0);
6509 consumedOperands = 2;
6510 break;
6511 case glslang::EOpSubBorrow:
6512 opCode = spv::OpISubBorrow;
6513 typeId = builder.makeStructResultType(typeId0, typeId0);
6514 consumedOperands = 2;
6515 break;
6516 case glslang::EOpUMulExtended:
6517 opCode = spv::OpUMulExtended;
6518 typeId = builder.makeStructResultType(typeId0, typeId0);
6519 consumedOperands = 2;
6520 break;
6521 case glslang::EOpIMulExtended:
6522 opCode = spv::OpSMulExtended;
6523 typeId = builder.makeStructResultType(typeId0, typeId0);
6524 consumedOperands = 2;
6525 break;
6526 case glslang::EOpBitfieldExtract:
6527 if (isUnsigned)
6528 opCode = spv::OpBitFieldUExtract;
6529 else
6530 opCode = spv::OpBitFieldSExtract;
6531 break;
6532 case glslang::EOpBitfieldInsert:
6533 opCode = spv::OpBitFieldInsert;
6534 break;
6535
6536 case glslang::EOpFma:
6537 libCall = spv::GLSLstd450Fma;
6538 break;
6539 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006540 {
6541 libCall = spv::GLSLstd450FrexpStruct;
6542 assert(builder.isPointerType(typeId1));
6543 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006544 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006545#ifdef AMD_EXTENSIONS
6546 if (width == 16)
6547 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6548 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6549#endif
Rex Xu470026f2017-03-29 17:12:40 +08006550 if (builder.getNumComponents(operands[0]) == 1)
6551 frexpIntType = builder.makeIntegerType(width, true);
6552 else
6553 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6554 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6555 consumedOperands = 1;
6556 }
John Kessenich55e7d112015-11-15 21:33:39 -07006557 break;
6558 case glslang::EOpLdexp:
6559 libCall = spv::GLSLstd450Ldexp;
6560 break;
6561
Rex Xu574ab042016-04-14 16:53:07 +08006562 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006563 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006564
John Kessenich66011cb2018-03-06 16:12:04 -07006565 case glslang::EOpSubgroupBroadcast:
6566 case glslang::EOpSubgroupBallotBitExtract:
6567 case glslang::EOpSubgroupShuffle:
6568 case glslang::EOpSubgroupShuffleXor:
6569 case glslang::EOpSubgroupShuffleUp:
6570 case glslang::EOpSubgroupShuffleDown:
6571 case glslang::EOpSubgroupClusteredAdd:
6572 case glslang::EOpSubgroupClusteredMul:
6573 case glslang::EOpSubgroupClusteredMin:
6574 case glslang::EOpSubgroupClusteredMax:
6575 case glslang::EOpSubgroupClusteredAnd:
6576 case glslang::EOpSubgroupClusteredOr:
6577 case glslang::EOpSubgroupClusteredXor:
6578 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006579#ifdef NV_EXTENSIONS
6580 case glslang::EOpSubgroupPartitionedAdd:
6581 case glslang::EOpSubgroupPartitionedMul:
6582 case glslang::EOpSubgroupPartitionedMin:
6583 case glslang::EOpSubgroupPartitionedMax:
6584 case glslang::EOpSubgroupPartitionedAnd:
6585 case glslang::EOpSubgroupPartitionedOr:
6586 case glslang::EOpSubgroupPartitionedXor:
6587 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6588 case glslang::EOpSubgroupPartitionedInclusiveMul:
6589 case glslang::EOpSubgroupPartitionedInclusiveMin:
6590 case glslang::EOpSubgroupPartitionedInclusiveMax:
6591 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6592 case glslang::EOpSubgroupPartitionedInclusiveOr:
6593 case glslang::EOpSubgroupPartitionedInclusiveXor:
6594 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6595 case glslang::EOpSubgroupPartitionedExclusiveMul:
6596 case glslang::EOpSubgroupPartitionedExclusiveMin:
6597 case glslang::EOpSubgroupPartitionedExclusiveMax:
6598 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6599 case glslang::EOpSubgroupPartitionedExclusiveOr:
6600 case glslang::EOpSubgroupPartitionedExclusiveXor:
6601#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006602 return createSubgroupOperation(op, typeId, operands, typeProxy);
6603
Rex Xu9d93a232016-05-05 12:30:44 +08006604#ifdef AMD_EXTENSIONS
6605 case glslang::EOpSwizzleInvocations:
6606 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6607 libCall = spv::SwizzleInvocationsAMD;
6608 break;
6609 case glslang::EOpSwizzleInvocationsMasked:
6610 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6611 libCall = spv::SwizzleInvocationsMaskedAMD;
6612 break;
6613 case glslang::EOpWriteInvocation:
6614 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6615 libCall = spv::WriteInvocationAMD;
6616 break;
6617
6618 case glslang::EOpMin3:
6619 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6620 if (isFloat)
6621 libCall = spv::FMin3AMD;
6622 else {
6623 if (isUnsigned)
6624 libCall = spv::UMin3AMD;
6625 else
6626 libCall = spv::SMin3AMD;
6627 }
6628 break;
6629 case glslang::EOpMax3:
6630 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6631 if (isFloat)
6632 libCall = spv::FMax3AMD;
6633 else {
6634 if (isUnsigned)
6635 libCall = spv::UMax3AMD;
6636 else
6637 libCall = spv::SMax3AMD;
6638 }
6639 break;
6640 case glslang::EOpMid3:
6641 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6642 if (isFloat)
6643 libCall = spv::FMid3AMD;
6644 else {
6645 if (isUnsigned)
6646 libCall = spv::UMid3AMD;
6647 else
6648 libCall = spv::SMid3AMD;
6649 }
6650 break;
6651
6652 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006653 if (typeProxy == glslang::EbtFloat16)
6654 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006655 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6656 libCall = spv::InterpolateAtVertexAMD;
6657 break;
6658#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006659 case glslang::EOpBarrier:
6660 {
6661 // This is for the extended controlBarrier function, with four operands.
6662 // The unextended barrier() goes through createNoArgOperation.
6663 assert(operands.size() == 4);
6664 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6665 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6666 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6667 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6668 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6669 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6670 }
6671 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6672 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6673 }
6674 return 0;
6675 }
6676 break;
6677 case glslang::EOpMemoryBarrier:
6678 {
6679 // This is for the extended memoryBarrier function, with three operands.
6680 // The unextended memoryBarrier() goes through createNoArgOperation.
6681 assert(operands.size() == 3);
6682 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6683 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6684 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6685 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6686 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6687 }
6688 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6689 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6690 }
6691 return 0;
6692 }
6693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006694 default:
6695 return 0;
6696 }
6697
6698 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006699 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006700 // Use an extended instruction from the standard library.
6701 // Construct the call arguments, without modifying the original operands vector.
6702 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6703 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006704 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006705 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006706 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006707 case 0:
6708 // should all be handled by visitAggregate and createNoArgOperation
6709 assert(0);
6710 return 0;
6711 case 1:
6712 // should all be handled by createUnaryOperation
6713 assert(0);
6714 return 0;
6715 case 2:
6716 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6717 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006718 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006719 // anything 3 or over doesn't have l-value operands, so all should be consumed
6720 assert(consumedOperands == operands.size());
6721 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006722 break;
6723 }
6724 }
6725
John Kessenich55e7d112015-11-15 21:33:39 -07006726 // Decode the return types that were structures
6727 switch (op) {
6728 case glslang::EOpAddCarry:
6729 case glslang::EOpSubBorrow:
6730 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6731 id = builder.createCompositeExtract(id, typeId0, 0);
6732 break;
6733 case glslang::EOpUMulExtended:
6734 case glslang::EOpIMulExtended:
6735 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6736 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6737 break;
6738 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006739 {
6740 assert(operands.size() == 2);
6741 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6742 // "exp" is floating-point type (from HLSL intrinsic)
6743 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6744 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6745 builder.createStore(member1, operands[1]);
6746 } else
6747 // "exp" is integer type (from GLSL built-in function)
6748 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6749 id = builder.createCompositeExtract(id, typeId0, 0);
6750 }
John Kessenich55e7d112015-11-15 21:33:39 -07006751 break;
6752 default:
6753 break;
6754 }
6755
John Kessenich32cfd492016-02-02 12:37:46 -07006756 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006757}
6758
Rex Xu9d93a232016-05-05 12:30:44 +08006759// Intrinsics with no arguments (or no return value, and no precision).
6760spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006761{
Jeff Bolz36831c92018-09-05 10:11:41 -05006762 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6763 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006764
6765 switch (op) {
6766 case glslang::EOpEmitVertex:
6767 builder.createNoResultOp(spv::OpEmitVertex);
6768 return 0;
6769 case glslang::EOpEndPrimitive:
6770 builder.createNoResultOp(spv::OpEndPrimitive);
6771 return 0;
6772 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006773 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006774 if (glslangIntermediate->usingVulkanMemoryModel()) {
6775 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6776 spv::MemorySemanticsOutputMemoryKHRMask |
6777 spv::MemorySemanticsAcquireReleaseMask);
6778 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6779 } else {
6780 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6781 }
John Kessenich82979362017-12-11 04:02:24 -07006782 } else {
6783 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6784 spv::MemorySemanticsWorkgroupMemoryMask |
6785 spv::MemorySemanticsAcquireReleaseMask);
6786 }
John Kessenich140f3df2015-06-26 16:58:36 -06006787 return 0;
6788 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006789 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6790 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006791 return 0;
6792 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006793 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6794 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006795 return 0;
6796 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006797 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6798 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006799 return 0;
6800 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006801 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6802 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006803 return 0;
6804 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006805 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6806 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006807 return 0;
6808 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006809 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6810 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006811 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006812 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006813 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006814 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006815 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006816 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006817 case glslang::EOpDeviceMemoryBarrier:
6818 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6819 spv::MemorySemanticsImageMemoryMask |
6820 spv::MemorySemanticsAcquireReleaseMask);
6821 return 0;
6822 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6823 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6824 spv::MemorySemanticsImageMemoryMask |
6825 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006826 return 0;
6827 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006828 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6829 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006830 return 0;
6831 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006832 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6833 spv::MemorySemanticsWorkgroupMemoryMask |
6834 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006835 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006836 case glslang::EOpSubgroupBarrier:
6837 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6838 spv::MemorySemanticsAcquireReleaseMask);
6839 return spv::NoResult;
6840 case glslang::EOpSubgroupMemoryBarrier:
6841 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6842 spv::MemorySemanticsAcquireReleaseMask);
6843 return spv::NoResult;
6844 case glslang::EOpSubgroupMemoryBarrierBuffer:
6845 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6846 spv::MemorySemanticsAcquireReleaseMask);
6847 return spv::NoResult;
6848 case glslang::EOpSubgroupMemoryBarrierImage:
6849 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6850 spv::MemorySemanticsAcquireReleaseMask);
6851 return spv::NoResult;
6852 case glslang::EOpSubgroupMemoryBarrierShared:
6853 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6854 spv::MemorySemanticsAcquireReleaseMask);
6855 return spv::NoResult;
6856 case glslang::EOpSubgroupElect: {
6857 std::vector<spv::Id> operands;
6858 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6859 }
Rex Xu9d93a232016-05-05 12:30:44 +08006860#ifdef AMD_EXTENSIONS
6861 case glslang::EOpTime:
6862 {
6863 std::vector<spv::Id> args; // Dummy arguments
6864 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6865 return builder.setPrecision(id, precision);
6866 }
6867#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006868 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006869 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006870 return 0;
6871 }
6872}
6873
6874spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6875{
John Kessenich2f273362015-07-18 22:34:27 -06006876 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006877 spv::Id id;
6878 if (symbolValues.end() != iter) {
6879 id = iter->second;
6880 return id;
6881 }
6882
6883 // it was not found, create it
6884 id = createSpvVariable(symbol);
6885 symbolValues[symbol->getId()] = id;
6886
Rex Xuc884b4a2016-06-29 15:03:44 +08006887 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006888 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6889 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6890 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006891 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006892 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006893 if (symbol->getQualifier().hasIndex())
6894 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6895 if (symbol->getQualifier().hasComponent())
6896 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006897 // atomic counters use this:
6898 if (symbol->getQualifier().hasOffset())
6899 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006900 }
6901
scygan2c864272016-05-18 18:09:17 +02006902 if (symbol->getQualifier().hasLocation())
6903 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006904 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006905 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006906 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006907 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006908 }
John Kessenich140f3df2015-06-26 16:58:36 -06006909 if (symbol->getQualifier().hasSet())
6910 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006911 else if (IsDescriptorResource(symbol->getType())) {
6912 // default to 0
6913 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6914 }
John Kessenich140f3df2015-06-26 16:58:36 -06006915 if (symbol->getQualifier().hasBinding())
6916 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006917 if (symbol->getQualifier().hasAttachment())
6918 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006919 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006920 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006921 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006922 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006923 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006924 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006925 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6926 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6927 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6928 }
6929 if (symbol->getQualifier().hasXfbOffset())
6930 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006931 }
6932
Rex Xu1da878f2016-02-21 20:59:01 +08006933 if (symbol->getType().isImage()) {
6934 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05006935 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08006936 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006937 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006938 }
6939
John Kessenich140f3df2015-06-26 16:58:36 -06006940 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006941 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006942 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006943 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006944
John Kessenich5611c6d2018-04-05 11:25:02 -06006945 // nonuniform
6946 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6947
John Kessenichecba76f2017-01-06 00:34:48 -07006948#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006949 if (builtIn == spv::BuiltInSampleMask) {
6950 spv::Decoration decoration;
6951 // GL_NV_sample_mask_override_coverage extension
6952 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006953 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006954 else
6955 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006956 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006957 if (decoration != spv::DecorationMax) {
6958 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6959 }
6960 }
chaoc771d89f2017-01-13 01:10:53 -08006961 else if (builtIn == spv::BuiltInLayer) {
6962 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006963 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006964 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006965 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6966 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6967 }
John Kessenichb41bff62017-08-11 13:07:17 -06006968 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006969 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6970 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006971 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6972 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6973 }
6974 }
6975
chaoc6e5acae2016-12-20 13:28:52 -08006976 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006977 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006978 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006979 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6980 }
Chao Chen9eada4b2018-09-19 11:39:56 -07006981 if (symbol->getQualifier().pervertexNV) {
6982 builder.addDecoration(id, spv::DecorationPerVertexNV);
6983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
6984 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
6985 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006986#endif
6987
John Kessenich5d610ee2018-03-07 18:05:55 -07006988 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6989 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6990 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6991 symbol->getType().getQualifier().semanticName);
6992 }
6993
John Kessenich140f3df2015-06-26 16:58:36 -06006994 return id;
6995}
6996
John Kessenich55e7d112015-11-15 21:33:39 -07006997// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006998// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006999//
7000// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7001//
7002// Recursively walk the nodes. The nodes form a tree whose leaves are
7003// regular constants, which themselves are trees that createSpvConstant()
7004// recursively walks. So, this function walks the "top" of the tree:
7005// - emit specialization constant-building instructions for specConstant
7006// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007007spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007008{
John Kessenich7cc0e282016-03-20 00:46:02 -06007009 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007010
qining4f4bb812016-04-03 23:55:17 -04007011 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007012 if (! node.getQualifier().specConstant) {
7013 // hand off to the non-spec-constant path
7014 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7015 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007016 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007017 nextConst, false);
7018 }
7019
7020 // We now know we have a specialization constant to build
7021
John Kessenichd94c0032016-05-30 19:29:40 -06007022 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007023 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7024 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7025 std::vector<spv::Id> dimConstId;
7026 for (int dim = 0; dim < 3; ++dim) {
7027 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7028 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007029 if (specConst) {
7030 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7031 glslangIntermediate->getLocalSizeSpecId(dim));
7032 }
qining4f4bb812016-04-03 23:55:17 -04007033 }
7034 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7035 }
7036
7037 // An AST node labelled as specialization constant should be a symbol node.
7038 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7039 if (auto* sn = node.getAsSymbolNode()) {
7040 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007041 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7042 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7043 // will set the builder into spec constant op instruction generating mode.
7044 sub_tree->traverse(this);
7045 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04007046 } else if (auto* const_union_array = &sn->getConstArray()){
7047 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01007048 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
7049 builder.addName(id, sn->getName().c_str());
7050 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07007051 }
7052 }
qining4f4bb812016-04-03 23:55:17 -04007053
7054 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7055 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007056 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007057 exit(1);
7058 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007059}
7060
John Kessenich140f3df2015-06-26 16:58:36 -06007061// Use 'consts' as the flattened glslang source of scalar constants to recursively
7062// build the aggregate SPIR-V constant.
7063//
7064// If there are not enough elements present in 'consts', 0 will be substituted;
7065// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7066//
qining08408382016-03-21 09:51:37 -04007067spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007068{
7069 // vector of constants for SPIR-V
7070 std::vector<spv::Id> spvConsts;
7071
7072 // Type is used for struct and array constants
7073 spv::Id typeId = convertGlslangToSpvType(glslangType);
7074
7075 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007076 glslang::TType elementType(glslangType, 0);
7077 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007078 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007079 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007080 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007081 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007082 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007083 } else if (glslangType.getStruct()) {
7084 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7085 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007086 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007087 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007088 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7089 bool zero = nextConst >= consts.size();
7090 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007091 case glslang::EbtInt8:
7092 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7093 break;
7094 case glslang::EbtUint8:
7095 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7096 break;
7097 case glslang::EbtInt16:
7098 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7099 break;
7100 case glslang::EbtUint16:
7101 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7102 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007103 case glslang::EbtInt:
7104 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7105 break;
7106 case glslang::EbtUint:
7107 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7108 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007109 case glslang::EbtInt64:
7110 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7111 break;
7112 case glslang::EbtUint64:
7113 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7114 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007115 case glslang::EbtFloat:
7116 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7117 break;
7118 case glslang::EbtDouble:
7119 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7120 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007121 case glslang::EbtFloat16:
7122 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7123 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007124 case glslang::EbtBool:
7125 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7126 break;
7127 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007128 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007129 break;
7130 }
7131 ++nextConst;
7132 }
7133 } else {
7134 // we have a non-aggregate (scalar) constant
7135 bool zero = nextConst >= consts.size();
7136 spv::Id scalar = 0;
7137 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007138 case glslang::EbtInt8:
7139 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7140 break;
7141 case glslang::EbtUint8:
7142 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7143 break;
7144 case glslang::EbtInt16:
7145 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7146 break;
7147 case glslang::EbtUint16:
7148 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7149 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007150 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007151 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007152 break;
7153 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007154 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007155 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007156 case glslang::EbtInt64:
7157 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7158 break;
7159 case glslang::EbtUint64:
7160 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7161 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007162 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007163 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007164 break;
7165 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007166 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007167 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007168 case glslang::EbtFloat16:
7169 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7170 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007171 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007172 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007173 break;
7174 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007175 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007176 break;
7177 }
7178 ++nextConst;
7179 return scalar;
7180 }
7181
7182 return builder.makeCompositeConstant(typeId, spvConsts);
7183}
7184
John Kessenich7c1aa102015-10-15 13:29:11 -06007185// Return true if the node is a constant or symbol whose reading has no
7186// non-trivial observable cost or effect.
7187bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7188{
7189 // don't know what this is
7190 if (node == nullptr)
7191 return false;
7192
7193 // a constant is safe
7194 if (node->getAsConstantUnion() != nullptr)
7195 return true;
7196
7197 // not a symbol means non-trivial
7198 if (node->getAsSymbolNode() == nullptr)
7199 return false;
7200
7201 // a symbol, depends on what's being read
7202 switch (node->getType().getQualifier().storage) {
7203 case glslang::EvqTemporary:
7204 case glslang::EvqGlobal:
7205 case glslang::EvqIn:
7206 case glslang::EvqInOut:
7207 case glslang::EvqConst:
7208 case glslang::EvqConstReadOnly:
7209 case glslang::EvqUniform:
7210 return true;
7211 default:
7212 return false;
7213 }
qining25262b32016-05-06 17:25:16 -04007214}
John Kessenich7c1aa102015-10-15 13:29:11 -06007215
7216// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007217// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007218// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007219// Return true if trivial.
7220bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7221{
7222 if (node == nullptr)
7223 return false;
7224
John Kessenich84cc15f2017-05-24 16:44:47 -06007225 // count non scalars as trivial, as well as anything coming from HLSL
7226 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007227 return true;
7228
John Kessenich7c1aa102015-10-15 13:29:11 -06007229 // symbols and constants are trivial
7230 if (isTrivialLeaf(node))
7231 return true;
7232
7233 // otherwise, it needs to be a simple operation or one or two leaf nodes
7234
7235 // not a simple operation
7236 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7237 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7238 if (binaryNode == nullptr && unaryNode == nullptr)
7239 return false;
7240
7241 // not on leaf nodes
7242 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7243 return false;
7244
7245 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7246 return false;
7247 }
7248
7249 switch (node->getAsOperator()->getOp()) {
7250 case glslang::EOpLogicalNot:
7251 case glslang::EOpConvIntToBool:
7252 case glslang::EOpConvUintToBool:
7253 case glslang::EOpConvFloatToBool:
7254 case glslang::EOpConvDoubleToBool:
7255 case glslang::EOpEqual:
7256 case glslang::EOpNotEqual:
7257 case glslang::EOpLessThan:
7258 case glslang::EOpGreaterThan:
7259 case glslang::EOpLessThanEqual:
7260 case glslang::EOpGreaterThanEqual:
7261 case glslang::EOpIndexDirect:
7262 case glslang::EOpIndexDirectStruct:
7263 case glslang::EOpLogicalXor:
7264 case glslang::EOpAny:
7265 case glslang::EOpAll:
7266 return true;
7267 default:
7268 return false;
7269 }
7270}
7271
7272// Emit short-circuiting code, where 'right' is never evaluated unless
7273// the left side is true (for &&) or false (for ||).
7274spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7275{
7276 spv::Id boolTypeId = builder.makeBoolType();
7277
7278 // emit left operand
7279 builder.clearAccessChain();
7280 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007281 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007282
7283 // Operands to accumulate OpPhi operands
7284 std::vector<spv::Id> phiOperands;
7285 // accumulate left operand's phi information
7286 phiOperands.push_back(leftId);
7287 phiOperands.push_back(builder.getBuildPoint()->getId());
7288
7289 // Make the two kinds of operation symmetric with a "!"
7290 // || => emit "if (! left) result = right"
7291 // && => emit "if ( left) result = right"
7292 //
7293 // TODO: this runtime "not" for || could be avoided by adding functionality
7294 // to 'builder' to have an "else" without an "then"
7295 if (op == glslang::EOpLogicalOr)
7296 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7297
7298 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007299 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007300
7301 // emit right operand as the "then" part of the "if"
7302 builder.clearAccessChain();
7303 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007304 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007305
7306 // accumulate left operand's phi information
7307 phiOperands.push_back(rightId);
7308 phiOperands.push_back(builder.getBuildPoint()->getId());
7309
7310 // finish the "if"
7311 ifBuilder.makeEndIf();
7312
7313 // phi together the two results
7314 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7315}
7316
Frank Henigman541f7bb2018-01-16 00:18:26 -05007317#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007318// Return type Id of the imported set of extended instructions corresponds to the name.
7319// Import this set if it has not been imported yet.
7320spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7321{
7322 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7323 return extBuiltinMap[name];
7324 else {
Rex Xu51596642016-09-21 18:56:12 +08007325 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007326 spv::Id extBuiltins = builder.import(name);
7327 extBuiltinMap[name] = extBuiltins;
7328 return extBuiltins;
7329 }
7330}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007331#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007332
John Kessenich140f3df2015-06-26 16:58:36 -06007333}; // end anonymous namespace
7334
7335namespace glslang {
7336
John Kessenich68d78fd2015-07-12 19:28:10 -06007337void GetSpirvVersion(std::string& version)
7338{
John Kessenich9e55f632015-07-15 10:03:39 -06007339 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007340 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007341 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007342 version = buf;
7343}
7344
John Kessenicha372a3e2017-11-02 22:32:14 -06007345// For low-order part of the generator's magic number. Bump up
7346// when there is a change in the style (e.g., if SSA form changes,
7347// or a different instruction sequence to do something gets used).
7348int GetSpirvGeneratorVersion()
7349{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007350 // return 1; // start
7351 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007352 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007353 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007354 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007355 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7356 // versions 4 and 6 each generate OpArrayLength as it has long been done
7357 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007358}
7359
John Kessenich140f3df2015-06-26 16:58:36 -06007360// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007361void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007362{
7363 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007364 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007365 if (out.fail())
7366 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007367 for (int i = 0; i < (int)spirv.size(); ++i) {
7368 unsigned int word = spirv[i];
7369 out.write((const char*)&word, 4);
7370 }
7371 out.close();
7372}
7373
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007374// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007375void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007376{
7377 std::ofstream out;
7378 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007379 if (out.fail())
7380 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007381 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007382 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007383 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007384 if (varName != nullptr) {
7385 out << "\t #pragma once" << std::endl;
7386 out << "const uint32_t " << varName << "[] = {" << std::endl;
7387 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007388 const int WORDS_PER_LINE = 8;
7389 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7390 out << "\t";
7391 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7392 const unsigned int word = spirv[i + j];
7393 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7394 if (i + j + 1 < (int)spirv.size()) {
7395 out << ",";
7396 }
7397 }
7398 out << std::endl;
7399 }
Flavio15017db2017-02-15 14:29:33 -08007400 if (varName != nullptr) {
7401 out << "};";
7402 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007403 out.close();
7404}
7405
John Kessenich140f3df2015-06-26 16:58:36 -06007406//
7407// Set up the glslang traversal
7408//
John Kessenich4e11b612018-08-30 16:56:59 -06007409void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007410{
Lei Zhang17535f72016-05-04 15:55:59 -04007411 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007412 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007413}
7414
John Kessenich4e11b612018-08-30 16:56:59 -06007415void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007416 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007417{
John Kessenich140f3df2015-06-26 16:58:36 -06007418 TIntermNode* root = intermediate.getTreeRoot();
7419
7420 if (root == 0)
7421 return;
7422
John Kessenich4e11b612018-08-30 16:56:59 -06007423 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007424 if (options == nullptr)
7425 options = &defaultOptions;
7426
John Kessenich4e11b612018-08-30 16:56:59 -06007427 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007428
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007429 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007430 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007431 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007432 it.dumpSpv(spirv);
7433
GregFfb03a552018-03-29 11:49:14 -06007434#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007435 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7436 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007437 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007438 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007439
John Kessenich4e11b612018-08-30 16:56:59 -06007440 if (options->validate)
7441 SpirvToolsValidate(intermediate, spirv, logger);
7442
John Kessenich717c80a2018-08-23 15:17:10 -06007443 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007444 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007445
GregFcd1f1692017-09-21 18:40:22 -06007446#endif
7447
John Kessenich4e11b612018-08-30 16:56:59 -06007448 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007449}
7450
7451}; // end namespace glslang