blob: c04a6c50b82a1c26d508a34928392af8e1ac9149 [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));
John Kessenich140f3df2015-06-26 16:58:36 -06001303 break;
1304
1305 default:
1306 break;
1307 }
John Kessenich140f3df2015-06-26 16:58:36 -06001308}
1309
John Kessenichfca82622016-11-26 13:23:20 -07001310// Finish creating SPV, after the traversal is complete.
1311void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001312{
John Kessenichf04c51b2018-08-03 15:56:12 -06001313 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001314 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001315 builder.setBuildPoint(shaderEntry->getLastBlock());
1316 builder.leaveFunction();
1317 }
1318
John Kessenich7ba63412015-12-20 17:37:07 -07001319 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001320 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1321 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001322
John Kessenichf04c51b2018-08-03 15:56:12 -06001323 // Add capabilities, extensions, remove unneeded decorations, etc.,
1324 // based on the resulting SPIR-V.
1325 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001326}
1327
John Kessenichfca82622016-11-26 13:23:20 -07001328// Write the SPV into 'out'.
1329void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001330{
John Kessenichfca82622016-11-26 13:23:20 -07001331 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001332}
1333
1334//
1335// Implement the traversal functions.
1336//
1337// Return true from interior nodes to have the external traversal
1338// continue on to children. Return false if children were
1339// already processed.
1340//
1341
1342//
qining25262b32016-05-06 17:25:16 -04001343// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001344// - uniform/input reads
1345// - output writes
1346// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1347// - something simple that degenerates into the last bullet
1348//
1349void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1350{
qining75d1d802016-04-06 14:42:01 -04001351 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1352 if (symbol->getType().getQualifier().isSpecConstant())
1353 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1354
John Kessenich140f3df2015-06-26 16:58:36 -06001355 // getSymbolId() will set up all the IO decorations on the first call.
1356 // Formal function parameters were mapped during makeFunctions().
1357 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001358
1359 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1360 if (builder.isPointer(id)) {
1361 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001362 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1363 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1364 iOSet.insert(id);
1365 }
John Kessenich7ba63412015-12-20 17:37:07 -07001366 }
1367
1368 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001369 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001370 // Prepare to generate code for the access
1371
1372 // L-value chains will be computed left to right. We're on the symbol now,
1373 // which is the left-most part of the access chain, so now is "clear" time,
1374 // followed by setting the base.
1375 builder.clearAccessChain();
1376
1377 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001378 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001379 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001380 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001381 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001382 // These are also pure R-values.
1383 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001384 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001385 builder.setAccessChainRValue(id);
1386 else
1387 builder.setAccessChainLValue(id);
1388 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001389
1390 // Process linkage-only nodes for any special additional interface work.
1391 if (linkageOnly) {
1392 if (glslangIntermediate->getHlslFunctionality1()) {
1393 // Map implicit counter buffers to their originating buffers, which should have been
1394 // seen by now, given earlier pruning of unused counters, and preservation of order
1395 // of declaration.
1396 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1397 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1398 // Save possible originating buffers for counter buffers, keyed by
1399 // making the potential counter-buffer name.
1400 std::string keyName = symbol->getName().c_str();
1401 keyName = glslangIntermediate->addCounterBufferName(keyName);
1402 counterOriginator[keyName] = symbol;
1403 } else {
1404 // Handle a counter buffer, by finding the saved originating buffer.
1405 std::string keyName = symbol->getName().c_str();
1406 auto it = counterOriginator.find(keyName);
1407 if (it != counterOriginator.end()) {
1408 id = getSymbolId(it->second);
1409 if (id != spv::NoResult) {
1410 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001411 if (counterId != spv::NoResult) {
1412 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001413 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001414 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001415 }
1416 }
1417 }
1418 }
1419 }
1420 }
John Kessenich140f3df2015-06-26 16:58:36 -06001421}
1422
1423bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1424{
John Kesseniche485c7a2017-05-31 18:50:53 -06001425 builder.setLine(node->getLoc().line);
1426
qining40887662016-04-03 22:20:42 -04001427 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1428 if (node->getType().getQualifier().isSpecConstant())
1429 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1430
John Kessenich140f3df2015-06-26 16:58:36 -06001431 // First, handle special cases
1432 switch (node->getOp()) {
1433 case glslang::EOpAssign:
1434 case glslang::EOpAddAssign:
1435 case glslang::EOpSubAssign:
1436 case glslang::EOpMulAssign:
1437 case glslang::EOpVectorTimesMatrixAssign:
1438 case glslang::EOpVectorTimesScalarAssign:
1439 case glslang::EOpMatrixTimesScalarAssign:
1440 case glslang::EOpMatrixTimesMatrixAssign:
1441 case glslang::EOpDivAssign:
1442 case glslang::EOpModAssign:
1443 case glslang::EOpAndAssign:
1444 case glslang::EOpInclusiveOrAssign:
1445 case glslang::EOpExclusiveOrAssign:
1446 case glslang::EOpLeftShiftAssign:
1447 case glslang::EOpRightShiftAssign:
1448 // A bin-op assign "a += b" means the same thing as "a = a + b"
1449 // where a is evaluated before b. For a simple assignment, GLSL
1450 // says to evaluate the left before the right. So, always, left
1451 // node then right node.
1452 {
1453 // get the left l-value, save it away
1454 builder.clearAccessChain();
1455 node->getLeft()->traverse(this);
1456 spv::Builder::AccessChain lValue = builder.getAccessChain();
1457
1458 // evaluate the right
1459 builder.clearAccessChain();
1460 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001461 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001462
1463 if (node->getOp() != glslang::EOpAssign) {
1464 // the left is also an r-value
1465 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001466 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001467
1468 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001469 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001470 TranslateNoContractionDecoration(node->getType().getQualifier()),
1471 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001472 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001473 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1474 node->getType().getBasicType());
1475
1476 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001477 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001478 }
1479
1480 // store the result
1481 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001482 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001483
1484 // assignments are expressions having an rValue after they are evaluated...
1485 builder.clearAccessChain();
1486 builder.setAccessChainRValue(rValue);
1487 }
1488 return false;
1489 case glslang::EOpIndexDirect:
1490 case glslang::EOpIndexDirectStruct:
1491 {
1492 // Get the left part of the access chain.
1493 node->getLeft()->traverse(this);
1494
1495 // Add the next element in the chain
1496
David Netoa901ffe2016-06-08 14:11:40 +01001497 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001498 if (! node->getLeft()->getType().isArray() &&
1499 node->getLeft()->getType().isVector() &&
1500 node->getOp() == glslang::EOpIndexDirect) {
1501 // This is essentially a hard-coded vector swizzle of size 1,
1502 // so short circuit the access-chain stuff with a swizzle.
1503 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001504 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001505 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001506 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001507 int spvIndex = glslangIndex;
1508 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1509 node->getOp() == glslang::EOpIndexDirectStruct)
1510 {
1511 // This may be, e.g., an anonymous block-member selection, which generally need
1512 // index remapping due to hidden members in anonymous blocks.
1513 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1514 assert(remapper.size() > 0);
1515 spvIndex = remapper[glslangIndex];
1516 }
John Kessenichebb50532016-05-16 19:22:05 -06001517
David Netoa901ffe2016-06-08 14:11:40 +01001518 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001519 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001520
1521 // Add capabilities here for accessing PointSize and clip/cull distance.
1522 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001523 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001524 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001525 }
1526 }
1527 return false;
1528 case glslang::EOpIndexIndirect:
1529 {
1530 // Structure or array or vector indirection.
1531 // Will use native SPIR-V access-chain for struct and array indirection;
1532 // matrices are arrays of vectors, so will also work for a matrix.
1533 // Will use the access chain's 'component' for variable index into a vector.
1534
1535 // This adapter is building access chains left to right.
1536 // Set up the access chain to the left.
1537 node->getLeft()->traverse(this);
1538
1539 // save it so that computing the right side doesn't trash it
1540 spv::Builder::AccessChain partial = builder.getAccessChain();
1541
1542 // compute the next index in the chain
1543 builder.clearAccessChain();
1544 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001545 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001546
John Kessenich5611c6d2018-04-05 11:25:02 -06001547 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1548
John Kessenich140f3df2015-06-26 16:58:36 -06001549 // restore the saved access chain
1550 builder.setAccessChain(partial);
1551
1552 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001553 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001554 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001555 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001556 }
1557 return false;
1558 case glslang::EOpVectorSwizzle:
1559 {
1560 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001562 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001563 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001564 }
1565 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001566 case glslang::EOpMatrixSwizzle:
1567 logger->missingFunctionality("matrix swizzle");
1568 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001569 case glslang::EOpLogicalOr:
1570 case glslang::EOpLogicalAnd:
1571 {
1572
1573 // These may require short circuiting, but can sometimes be done as straight
1574 // binary operations. The right operand must be short circuited if it has
1575 // side effects, and should probably be if it is complex.
1576 if (isTrivial(node->getRight()->getAsTyped()))
1577 break; // handle below as a normal binary operation
1578 // otherwise, we need to do dynamic short circuiting on the right operand
1579 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1580 builder.clearAccessChain();
1581 builder.setAccessChainRValue(result);
1582 }
1583 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001584 default:
1585 break;
1586 }
1587
1588 // Assume generic binary op...
1589
John Kessenich32cfd492016-02-02 12:37:46 -07001590 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001591 builder.clearAccessChain();
1592 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001593 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001594
John Kessenich32cfd492016-02-02 12:37:46 -07001595 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001596 builder.clearAccessChain();
1597 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001598 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001599
John Kessenich32cfd492016-02-02 12:37:46 -07001600 // get result
John Kessenichead86222018-03-28 18:01:20 -06001601 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001602 TranslateNoContractionDecoration(node->getType().getQualifier()),
1603 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001604 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001605 convertGlslangToSpvType(node->getType()), left, right,
1606 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001607
John Kessenich50e57562015-12-21 21:21:11 -07001608 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001609 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001610 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001611 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001612 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001613 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001614 return false;
1615 }
John Kessenich140f3df2015-06-26 16:58:36 -06001616}
1617
1618bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1619{
John Kesseniche485c7a2017-05-31 18:50:53 -06001620 builder.setLine(node->getLoc().line);
1621
qining40887662016-04-03 22:20:42 -04001622 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1623 if (node->getType().getQualifier().isSpecConstant())
1624 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1625
John Kessenichfc51d282015-08-19 13:34:18 -06001626 spv::Id result = spv::NoResult;
1627
1628 // try texturing first
1629 result = createImageTextureFunctionCall(node);
1630 if (result != spv::NoResult) {
1631 builder.clearAccessChain();
1632 builder.setAccessChainRValue(result);
1633
1634 return false; // done with this node
1635 }
1636
1637 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001638
1639 if (node->getOp() == glslang::EOpArrayLength) {
1640 // Quite special; won't want to evaluate the operand.
1641
John Kessenich5611c6d2018-04-05 11:25:02 -06001642 // Currently, the front-end does not allow .length() on an array until it is sized,
1643 // except for the last block membeor of an SSBO.
1644 // TODO: If this changes, link-time sized arrays might show up here, and need their
1645 // size extracted.
1646
John Kessenichc9a80832015-09-12 12:17:44 -06001647 // Normal .length() would have been constant folded by the front-end.
1648 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001649 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001650
John Kessenichc9a80832015-09-12 12:17:44 -06001651 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1652 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001653 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1654 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001655
1656 builder.clearAccessChain();
1657 builder.setAccessChainRValue(length);
1658
1659 return false;
1660 }
1661
John Kessenichfc51d282015-08-19 13:34:18 -06001662 // Start by evaluating the operand
1663
John Kessenich8c8505c2016-07-26 12:50:38 -06001664 // Does it need a swizzle inversion? If so, evaluation is inverted;
1665 // operate first on the swizzle base, then apply the swizzle.
1666 spv::Id invertedType = spv::NoType;
1667 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1668 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1669 invertedType = getInvertedSwizzleType(*node->getOperand());
1670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001672 if (invertedType != spv::NoType)
1673 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1674 else
1675 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001676
Rex Xufc618912015-09-09 16:42:49 +08001677 spv::Id operand = spv::NoResult;
1678
1679 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1680 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001681 node->getOp() == glslang::EOpAtomicCounter ||
1682 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001683 operand = builder.accessChainGetLValue(); // Special case l-value operands
1684 else
John Kessenich32cfd492016-02-02 12:37:46 -07001685 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
John Kessenichead86222018-03-28 18:01:20 -06001687 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001688 TranslateNoContractionDecoration(node->getType().getQualifier()),
1689 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001690
1691 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001692 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001693 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001694
1695 // if not, then possibly an operation
1696 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001697 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001698
1699 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001700 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001701 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001702 builder.addDecoration(result, decorations.nonUniform);
1703 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001704
John Kessenich140f3df2015-06-26 16:58:36 -06001705 builder.clearAccessChain();
1706 builder.setAccessChainRValue(result);
1707
1708 return false; // done with this node
1709 }
1710
1711 // it must be a special case, check...
1712 switch (node->getOp()) {
1713 case glslang::EOpPostIncrement:
1714 case glslang::EOpPostDecrement:
1715 case glslang::EOpPreIncrement:
1716 case glslang::EOpPreDecrement:
1717 {
1718 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001719 spv::Id one = 0;
1720 if (node->getBasicType() == glslang::EbtFloat)
1721 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001722 else if (node->getBasicType() == glslang::EbtDouble)
1723 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001724 else if (node->getBasicType() == glslang::EbtFloat16)
1725 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001726 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1727 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001728 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1729 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001730 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1731 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001732 else
1733 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001734 glslang::TOperator op;
1735 if (node->getOp() == glslang::EOpPreIncrement ||
1736 node->getOp() == glslang::EOpPostIncrement)
1737 op = glslang::EOpAdd;
1738 else
1739 op = glslang::EOpSub;
1740
John Kessenichead86222018-03-28 18:01:20 -06001741 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001742 convertGlslangToSpvType(node->getType()), operand, one,
1743 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001744 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001745
1746 // The result of operation is always stored, but conditionally the
1747 // consumed result. The consumed result is always an r-value.
1748 builder.accessChainStore(result);
1749 builder.clearAccessChain();
1750 if (node->getOp() == glslang::EOpPreIncrement ||
1751 node->getOp() == glslang::EOpPreDecrement)
1752 builder.setAccessChainRValue(result);
1753 else
1754 builder.setAccessChainRValue(operand);
1755 }
1756
1757 return false;
1758
1759 case glslang::EOpEmitStreamVertex:
1760 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1761 return false;
1762 case glslang::EOpEndStreamPrimitive:
1763 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1764 return false;
1765
1766 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001767 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001768 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001769 }
John Kessenich140f3df2015-06-26 16:58:36 -06001770}
1771
1772bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1773{
qining27e04a02016-04-14 16:40:20 -04001774 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1775 if (node->getType().getQualifier().isSpecConstant())
1776 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1777
John Kessenichfc51d282015-08-19 13:34:18 -06001778 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001779 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1780 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001781
1782 // try texturing
1783 result = createImageTextureFunctionCall(node);
1784 if (result != spv::NoResult) {
1785 builder.clearAccessChain();
1786 builder.setAccessChainRValue(result);
1787
1788 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001789 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001790#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001791 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001792#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001793 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001794 // "imageStore" is a special case, which has no result
1795 return false;
1796 }
John Kessenichfc51d282015-08-19 13:34:18 -06001797
John Kessenich140f3df2015-06-26 16:58:36 -06001798 glslang::TOperator binOp = glslang::EOpNull;
1799 bool reduceComparison = true;
1800 bool isMatrix = false;
1801 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001802 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001803
1804 assert(node->getOp());
1805
John Kessenichf6640762016-08-01 19:44:00 -06001806 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001807
1808 switch (node->getOp()) {
1809 case glslang::EOpSequence:
1810 {
1811 if (preVisit)
1812 ++sequenceDepth;
1813 else
1814 --sequenceDepth;
1815
1816 if (sequenceDepth == 1) {
1817 // If this is the parent node of all the functions, we want to see them
1818 // early, so all call points have actual SPIR-V functions to reference.
1819 // In all cases, still let the traverser visit the children for us.
1820 makeFunctions(node->getAsAggregate()->getSequence());
1821
John Kessenich6fccb3c2016-09-19 16:01:41 -06001822 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001823 // anything else gets there, so visit out of order, doing them all now.
1824 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1825
John Kessenich6a60c2f2016-12-08 21:01:59 -07001826 // 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 -06001827 // so do them manually.
1828 visitFunctions(node->getAsAggregate()->getSequence());
1829
1830 return false;
1831 }
1832
1833 return true;
1834 }
1835 case glslang::EOpLinkerObjects:
1836 {
1837 if (visit == glslang::EvPreVisit)
1838 linkageOnly = true;
1839 else
1840 linkageOnly = false;
1841
1842 return true;
1843 }
1844 case glslang::EOpComma:
1845 {
1846 // processing from left to right naturally leaves the right-most
1847 // lying around in the access chain
1848 glslang::TIntermSequence& glslangOperands = node->getSequence();
1849 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1850 glslangOperands[i]->traverse(this);
1851
1852 return false;
1853 }
1854 case glslang::EOpFunction:
1855 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001856 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001857 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001858 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001859 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001860 } else {
1861 handleFunctionEntry(node);
1862 }
1863 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001864 if (inEntryPoint)
1865 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001866 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001867 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
1869
1870 return true;
1871 case glslang::EOpParameters:
1872 // Parameters will have been consumed by EOpFunction processing, but not
1873 // the body, so we still visited the function node's children, making this
1874 // child redundant.
1875 return false;
1876 case glslang::EOpFunctionCall:
1877 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001878 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 if (node->isUserDefined())
1880 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001881 // 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 -07001882 if (result) {
1883 builder.clearAccessChain();
1884 builder.setAccessChainRValue(result);
1885 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001886 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001887
1888 return false;
1889 }
1890 case glslang::EOpConstructMat2x2:
1891 case glslang::EOpConstructMat2x3:
1892 case glslang::EOpConstructMat2x4:
1893 case glslang::EOpConstructMat3x2:
1894 case glslang::EOpConstructMat3x3:
1895 case glslang::EOpConstructMat3x4:
1896 case glslang::EOpConstructMat4x2:
1897 case glslang::EOpConstructMat4x3:
1898 case glslang::EOpConstructMat4x4:
1899 case glslang::EOpConstructDMat2x2:
1900 case glslang::EOpConstructDMat2x3:
1901 case glslang::EOpConstructDMat2x4:
1902 case glslang::EOpConstructDMat3x2:
1903 case glslang::EOpConstructDMat3x3:
1904 case glslang::EOpConstructDMat3x4:
1905 case glslang::EOpConstructDMat4x2:
1906 case glslang::EOpConstructDMat4x3:
1907 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001908 case glslang::EOpConstructIMat2x2:
1909 case glslang::EOpConstructIMat2x3:
1910 case glslang::EOpConstructIMat2x4:
1911 case glslang::EOpConstructIMat3x2:
1912 case glslang::EOpConstructIMat3x3:
1913 case glslang::EOpConstructIMat3x4:
1914 case glslang::EOpConstructIMat4x2:
1915 case glslang::EOpConstructIMat4x3:
1916 case glslang::EOpConstructIMat4x4:
1917 case glslang::EOpConstructUMat2x2:
1918 case glslang::EOpConstructUMat2x3:
1919 case glslang::EOpConstructUMat2x4:
1920 case glslang::EOpConstructUMat3x2:
1921 case glslang::EOpConstructUMat3x3:
1922 case glslang::EOpConstructUMat3x4:
1923 case glslang::EOpConstructUMat4x2:
1924 case glslang::EOpConstructUMat4x3:
1925 case glslang::EOpConstructUMat4x4:
1926 case glslang::EOpConstructBMat2x2:
1927 case glslang::EOpConstructBMat2x3:
1928 case glslang::EOpConstructBMat2x4:
1929 case glslang::EOpConstructBMat3x2:
1930 case glslang::EOpConstructBMat3x3:
1931 case glslang::EOpConstructBMat3x4:
1932 case glslang::EOpConstructBMat4x2:
1933 case glslang::EOpConstructBMat4x3:
1934 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001935 case glslang::EOpConstructF16Mat2x2:
1936 case glslang::EOpConstructF16Mat2x3:
1937 case glslang::EOpConstructF16Mat2x4:
1938 case glslang::EOpConstructF16Mat3x2:
1939 case glslang::EOpConstructF16Mat3x3:
1940 case glslang::EOpConstructF16Mat3x4:
1941 case glslang::EOpConstructF16Mat4x2:
1942 case glslang::EOpConstructF16Mat4x3:
1943 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001944 isMatrix = true;
1945 // fall through
1946 case glslang::EOpConstructFloat:
1947 case glslang::EOpConstructVec2:
1948 case glslang::EOpConstructVec3:
1949 case glslang::EOpConstructVec4:
1950 case glslang::EOpConstructDouble:
1951 case glslang::EOpConstructDVec2:
1952 case glslang::EOpConstructDVec3:
1953 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001954 case glslang::EOpConstructFloat16:
1955 case glslang::EOpConstructF16Vec2:
1956 case glslang::EOpConstructF16Vec3:
1957 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001958 case glslang::EOpConstructBool:
1959 case glslang::EOpConstructBVec2:
1960 case glslang::EOpConstructBVec3:
1961 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001962 case glslang::EOpConstructInt8:
1963 case glslang::EOpConstructI8Vec2:
1964 case glslang::EOpConstructI8Vec3:
1965 case glslang::EOpConstructI8Vec4:
1966 case glslang::EOpConstructUint8:
1967 case glslang::EOpConstructU8Vec2:
1968 case glslang::EOpConstructU8Vec3:
1969 case glslang::EOpConstructU8Vec4:
1970 case glslang::EOpConstructInt16:
1971 case glslang::EOpConstructI16Vec2:
1972 case glslang::EOpConstructI16Vec3:
1973 case glslang::EOpConstructI16Vec4:
1974 case glslang::EOpConstructUint16:
1975 case glslang::EOpConstructU16Vec2:
1976 case glslang::EOpConstructU16Vec3:
1977 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001978 case glslang::EOpConstructInt:
1979 case glslang::EOpConstructIVec2:
1980 case glslang::EOpConstructIVec3:
1981 case glslang::EOpConstructIVec4:
1982 case glslang::EOpConstructUint:
1983 case glslang::EOpConstructUVec2:
1984 case glslang::EOpConstructUVec3:
1985 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001986 case glslang::EOpConstructInt64:
1987 case glslang::EOpConstructI64Vec2:
1988 case glslang::EOpConstructI64Vec3:
1989 case glslang::EOpConstructI64Vec4:
1990 case glslang::EOpConstructUint64:
1991 case glslang::EOpConstructU64Vec2:
1992 case glslang::EOpConstructU64Vec3:
1993 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001994 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001995 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001996 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001997 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001998 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001999 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002000 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002001 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002002 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002003 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002004 std::vector<spv::Id> constituents;
2005 for (int c = 0; c < (int)arguments.size(); ++c)
2006 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002007 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002008 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002009 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002010 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002011 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002012
2013 builder.clearAccessChain();
2014 builder.setAccessChainRValue(constructed);
2015
2016 return false;
2017 }
2018
2019 // These six are component-wise compares with component-wise results.
2020 // Forward on to createBinaryOperation(), requesting a vector result.
2021 case glslang::EOpLessThan:
2022 case glslang::EOpGreaterThan:
2023 case glslang::EOpLessThanEqual:
2024 case glslang::EOpGreaterThanEqual:
2025 case glslang::EOpVectorEqual:
2026 case glslang::EOpVectorNotEqual:
2027 {
2028 // Map the operation to a binary
2029 binOp = node->getOp();
2030 reduceComparison = false;
2031 switch (node->getOp()) {
2032 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2033 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2034 default: binOp = node->getOp(); break;
2035 }
2036
2037 break;
2038 }
2039 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002040 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002041 binOp = glslang::EOpMul;
2042 break;
2043 case glslang::EOpOuterProduct:
2044 // two vectors multiplied to make a matrix
2045 binOp = glslang::EOpOuterProduct;
2046 break;
2047 case glslang::EOpDot:
2048 {
qining25262b32016-05-06 17:25:16 -04002049 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002050 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002051 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002052 binOp = glslang::EOpMul;
2053 break;
2054 }
2055 case glslang::EOpMod:
2056 // when an aggregate, this is the floating-point mod built-in function,
2057 // which can be emitted by the one in createBinaryOperation()
2058 binOp = glslang::EOpMod;
2059 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002060 case glslang::EOpEmitVertex:
2061 case glslang::EOpEndPrimitive:
2062 case glslang::EOpBarrier:
2063 case glslang::EOpMemoryBarrier:
2064 case glslang::EOpMemoryBarrierAtomicCounter:
2065 case glslang::EOpMemoryBarrierBuffer:
2066 case glslang::EOpMemoryBarrierImage:
2067 case glslang::EOpMemoryBarrierShared:
2068 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002069 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002070 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002071 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002072 case glslang::EOpWorkgroupMemoryBarrier:
2073 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002074 case glslang::EOpSubgroupBarrier:
2075 case glslang::EOpSubgroupMemoryBarrier:
2076 case glslang::EOpSubgroupMemoryBarrierBuffer:
2077 case glslang::EOpSubgroupMemoryBarrierImage:
2078 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002079 noReturnValue = true;
2080 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2081 break;
2082
Jeff Bolz36831c92018-09-05 10:11:41 -05002083 case glslang::EOpAtomicStore:
2084 noReturnValue = true;
2085 // fallthrough
2086 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002087 case glslang::EOpAtomicAdd:
2088 case glslang::EOpAtomicMin:
2089 case glslang::EOpAtomicMax:
2090 case glslang::EOpAtomicAnd:
2091 case glslang::EOpAtomicOr:
2092 case glslang::EOpAtomicXor:
2093 case glslang::EOpAtomicExchange:
2094 case glslang::EOpAtomicCompSwap:
2095 atomic = true;
2096 break;
2097
John Kessenich0d0c6d32017-07-23 16:08:26 -06002098 case glslang::EOpAtomicCounterAdd:
2099 case glslang::EOpAtomicCounterSubtract:
2100 case glslang::EOpAtomicCounterMin:
2101 case glslang::EOpAtomicCounterMax:
2102 case glslang::EOpAtomicCounterAnd:
2103 case glslang::EOpAtomicCounterOr:
2104 case glslang::EOpAtomicCounterXor:
2105 case glslang::EOpAtomicCounterExchange:
2106 case glslang::EOpAtomicCounterCompSwap:
2107 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2108 builder.addCapability(spv::CapabilityAtomicStorageOps);
2109 atomic = true;
2110 break;
2111
John Kessenich140f3df2015-06-26 16:58:36 -06002112 default:
2113 break;
2114 }
2115
2116 //
2117 // See if it maps to a regular operation.
2118 //
John Kessenich140f3df2015-06-26 16:58:36 -06002119 if (binOp != glslang::EOpNull) {
2120 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2121 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2122 assert(left && right);
2123
2124 builder.clearAccessChain();
2125 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002126 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002127
2128 builder.clearAccessChain();
2129 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002130 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002131
John Kesseniche485c7a2017-05-31 18:50:53 -06002132 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002133 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002134 TranslateNoContractionDecoration(node->getType().getQualifier()),
2135 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002136 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002137 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002138 left->getType().getBasicType(), reduceComparison);
2139
2140 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002141 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002142 builder.clearAccessChain();
2143 builder.setAccessChainRValue(result);
2144
2145 return false;
2146 }
2147
John Kessenich426394d2015-07-23 10:22:48 -06002148 //
2149 // Create the list of operands.
2150 //
John Kessenich140f3df2015-06-26 16:58:36 -06002151 glslang::TIntermSequence& glslangOperands = node->getSequence();
2152 std::vector<spv::Id> operands;
2153 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002154 // special case l-value operands; there are just a few
2155 bool lvalue = false;
2156 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002157 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002158 case glslang::EOpModf:
2159 if (arg == 1)
2160 lvalue = true;
2161 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002162 case glslang::EOpInterpolateAtSample:
2163 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002164#ifdef AMD_EXTENSIONS
2165 case glslang::EOpInterpolateAtVertex:
2166#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002167 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002168 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002169
2170 // Does it need a swizzle inversion? If so, evaluation is inverted;
2171 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002172 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002173 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2174 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2175 }
Rex Xu7a26c172015-12-08 17:12:09 +08002176 break;
Rex Xud4782c12015-09-06 16:30:11 +08002177 case glslang::EOpAtomicAdd:
2178 case glslang::EOpAtomicMin:
2179 case glslang::EOpAtomicMax:
2180 case glslang::EOpAtomicAnd:
2181 case glslang::EOpAtomicOr:
2182 case glslang::EOpAtomicXor:
2183 case glslang::EOpAtomicExchange:
2184 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002185 case glslang::EOpAtomicLoad:
2186 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002187 case glslang::EOpAtomicCounterAdd:
2188 case glslang::EOpAtomicCounterSubtract:
2189 case glslang::EOpAtomicCounterMin:
2190 case glslang::EOpAtomicCounterMax:
2191 case glslang::EOpAtomicCounterAnd:
2192 case glslang::EOpAtomicCounterOr:
2193 case glslang::EOpAtomicCounterXor:
2194 case glslang::EOpAtomicCounterExchange:
2195 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002196 if (arg == 0)
2197 lvalue = true;
2198 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002199 case glslang::EOpAddCarry:
2200 case glslang::EOpSubBorrow:
2201 if (arg == 2)
2202 lvalue = true;
2203 break;
2204 case glslang::EOpUMulExtended:
2205 case glslang::EOpIMulExtended:
2206 if (arg >= 2)
2207 lvalue = true;
2208 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002209 default:
2210 break;
2211 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002212 builder.clearAccessChain();
2213 if (invertedType != spv::NoType && arg == 0)
2214 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2215 else
2216 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002217 if (lvalue)
2218 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002219 else {
2220 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002221 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002222 }
John Kessenich140f3df2015-06-26 16:58:36 -06002223 }
John Kessenich426394d2015-07-23 10:22:48 -06002224
John Kesseniche485c7a2017-05-31 18:50:53 -06002225 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002226 if (atomic) {
2227 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002228 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002229 } else {
2230 // Pass through to generic operations.
2231 switch (glslangOperands.size()) {
2232 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002233 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002234 break;
2235 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002236 {
2237 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002238 TranslateNoContractionDecoration(node->getType().getQualifier()),
2239 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002240 result = createUnaryOperation(
2241 node->getOp(), decorations,
2242 resultType(), operands.front(),
2243 glslangOperands[0]->getAsTyped()->getBasicType());
2244 }
John Kessenich426394d2015-07-23 10:22:48 -06002245 break;
2246 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002247 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002248 break;
2249 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002250 if (invertedType)
2251 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002252 }
2253
2254 if (noReturnValue)
2255 return false;
2256
2257 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002258 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002259 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002260 } else {
2261 builder.clearAccessChain();
2262 builder.setAccessChainRValue(result);
2263 return false;
2264 }
2265}
2266
John Kessenich433e9ff2017-01-26 20:31:11 -07002267// This path handles both if-then-else and ?:
2268// The if-then-else has a node type of void, while
2269// ?: has either a void or a non-void node type
2270//
2271// Leaving the result, when not void:
2272// GLSL only has r-values as the result of a :?, but
2273// if we have an l-value, that can be more efficient if it will
2274// become the base of a complex r-value expression, because the
2275// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002276bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2277{
John Kessenich4bee5312018-02-20 21:29:05 -07002278 // See if it simple and safe, or required, to execute both sides.
2279 // Crucially, side effects must be either semantically required or avoided,
2280 // and there are performance trade-offs.
2281 // Return true if required or a good idea (and safe) to execute both sides,
2282 // false otherwise.
2283 const auto bothSidesPolicy = [&]() -> bool {
2284 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002285 if (node->getTrueBlock() == nullptr ||
2286 node->getFalseBlock() == nullptr)
2287 return false;
2288
John Kessenich4bee5312018-02-20 21:29:05 -07002289 // required? (unless we write additional code to look for side effects
2290 // and make performance trade-offs if none are present)
2291 if (!node->getShortCircuit())
2292 return true;
2293
2294 // if not required to execute both, decide based on performance/practicality...
2295
2296 // see if OpSelect can handle it
2297 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2298 node->getBasicType() == glslang::EbtVoid)
2299 return false;
2300
John Kessenich433e9ff2017-01-26 20:31:11 -07002301 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2302 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2303
2304 // return true if a single operand to ? : is okay for OpSelect
2305 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002306 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002307 };
2308
2309 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2310 operandOkay(node->getFalseBlock()->getAsTyped());
2311 };
2312
John Kessenich4bee5312018-02-20 21:29:05 -07002313 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2314 // emit the condition before doing anything with selection
2315 node->getCondition()->traverse(this);
2316 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2317
2318 // Find a way of executing both sides and selecting the right result.
2319 const auto executeBothSides = [&]() -> void {
2320 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002321 node->getTrueBlock()->traverse(this);
2322 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2323 node->getFalseBlock()->traverse(this);
2324 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2325
John Kesseniche485c7a2017-05-31 18:50:53 -06002326 builder.setLine(node->getLoc().line);
2327
John Kessenich4bee5312018-02-20 21:29:05 -07002328 // done if void
2329 if (node->getBasicType() == glslang::EbtVoid)
2330 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002331
John Kessenich4bee5312018-02-20 21:29:05 -07002332 // emit code to select between trueValue and falseValue
2333
2334 // see if OpSelect can handle it
2335 if (node->getType().isScalar() || node->getType().isVector()) {
2336 // Emit OpSelect for this selection.
2337
2338 // smear condition to vector, if necessary (AST is always scalar)
2339 if (builder.isVector(trueValue))
2340 condition = builder.smearScalar(spv::NoPrecision, condition,
2341 builder.makeVectorType(builder.makeBoolType(),
2342 builder.getNumComponents(trueValue)));
2343
2344 // OpSelect
2345 result = builder.createTriOp(spv::OpSelect,
2346 convertGlslangToSpvType(node->getType()), condition,
2347 trueValue, falseValue);
2348
2349 builder.clearAccessChain();
2350 builder.setAccessChainRValue(result);
2351 } else {
2352 // We need control flow to select the result.
2353 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2354 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2355
2356 // Selection control:
2357 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2358
2359 // make an "if" based on the value created by the condition
2360 spv::Builder::If ifBuilder(condition, control, builder);
2361
2362 // emit the "then" statement
2363 builder.createStore(trueValue, result);
2364 ifBuilder.makeBeginElse();
2365 // emit the "else" statement
2366 builder.createStore(falseValue, result);
2367
2368 // finish off the control flow
2369 ifBuilder.makeEndIf();
2370
2371 builder.clearAccessChain();
2372 builder.setAccessChainLValue(result);
2373 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002374 };
2375
John Kessenich4bee5312018-02-20 21:29:05 -07002376 // Execute the one side needed, as per the condition
2377 const auto executeOneSide = [&]() {
2378 // Always emit control flow.
2379 if (node->getBasicType() != glslang::EbtVoid)
2380 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002381
John Kessenich4bee5312018-02-20 21:29:05 -07002382 // Selection control:
2383 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2384
2385 // make an "if" based on the value created by the condition
2386 spv::Builder::If ifBuilder(condition, control, builder);
2387
2388 // emit the "then" statement
2389 if (node->getTrueBlock() != nullptr) {
2390 node->getTrueBlock()->traverse(this);
2391 if (result != spv::NoResult)
2392 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2393 }
2394
2395 if (node->getFalseBlock() != nullptr) {
2396 ifBuilder.makeBeginElse();
2397 // emit the "else" statement
2398 node->getFalseBlock()->traverse(this);
2399 if (result != spv::NoResult)
2400 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2401 }
2402
2403 // finish off the control flow
2404 ifBuilder.makeEndIf();
2405
2406 if (result != spv::NoResult) {
2407 builder.clearAccessChain();
2408 builder.setAccessChainLValue(result);
2409 }
2410 };
2411
2412 // Try for OpSelect (or a requirement to execute both sides)
2413 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002414 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2415 if (node->getType().getQualifier().isSpecConstant())
2416 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002417 executeBothSides();
2418 } else
2419 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002420
2421 return false;
2422}
2423
2424bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2425{
2426 // emit and get the condition before doing anything with switch
2427 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002428 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002429
Rex Xu57e65922017-07-04 23:23:40 +08002430 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002431 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002432
John Kessenich140f3df2015-06-26 16:58:36 -06002433 // browse the children to sort out code segments
2434 int defaultSegment = -1;
2435 std::vector<TIntermNode*> codeSegments;
2436 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2437 std::vector<int> caseValues;
2438 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2439 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2440 TIntermNode* child = *c;
2441 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002442 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002443 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002444 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002445 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2446 } else
2447 codeSegments.push_back(child);
2448 }
2449
qining25262b32016-05-06 17:25:16 -04002450 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002451 // statements between the last case and the end of the switch statement
2452 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2453 (int)codeSegments.size() == defaultSegment)
2454 codeSegments.push_back(nullptr);
2455
2456 // make the switch statement
2457 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002458 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002459
2460 // emit all the code in the segments
2461 breakForLoop.push(false);
2462 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2463 builder.nextSwitchSegment(segmentBlocks, s);
2464 if (codeSegments[s])
2465 codeSegments[s]->traverse(this);
2466 else
2467 builder.addSwitchBreak();
2468 }
2469 breakForLoop.pop();
2470
2471 builder.endSwitch(segmentBlocks);
2472
2473 return false;
2474}
2475
2476void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2477{
2478 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002479 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002480
2481 builder.clearAccessChain();
2482 builder.setAccessChainRValue(constant);
2483}
2484
2485bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2486{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002487 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002488 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002489
2490 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002491 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2492 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002493
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002494 // Spec requires back edges to target header blocks, and every header block
2495 // must dominate its merge block. Make a header block first to ensure these
2496 // conditions are met. By definition, it will contain OpLoopMerge, followed
2497 // by a block-ending branch. But we don't want to put any other body/test
2498 // instructions in it, since the body/test may have arbitrary instructions,
2499 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002500 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002501 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002502 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002503 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002504 spv::Block& test = builder.makeNewBlock();
2505 builder.createBranch(&test);
2506
2507 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002508 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002509 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002510 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2511
2512 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002513 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002514 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002515 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002516 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002517 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002518
2519 builder.setBuildPoint(&blocks.continue_target);
2520 if (node->getTerminal())
2521 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002522 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002523 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002524 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002525 builder.createBranch(&blocks.body);
2526
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002527 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002528 builder.setBuildPoint(&blocks.body);
2529 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002530 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002531 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002532 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002533
2534 builder.setBuildPoint(&blocks.continue_target);
2535 if (node->getTerminal())
2536 node->getTerminal()->traverse(this);
2537 if (node->getTest()) {
2538 node->getTest()->traverse(this);
2539 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002540 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002541 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002542 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002543 // TODO: unless there was a break/return/discard instruction
2544 // somewhere in the body, this is an infinite loop, so we should
2545 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002546 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002547 }
John Kessenich140f3df2015-06-26 16:58:36 -06002548 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002549 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002550 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002551 return false;
2552}
2553
2554bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2555{
2556 if (node->getExpression())
2557 node->getExpression()->traverse(this);
2558
John Kesseniche485c7a2017-05-31 18:50:53 -06002559 builder.setLine(node->getLoc().line);
2560
John Kessenich140f3df2015-06-26 16:58:36 -06002561 switch (node->getFlowOp()) {
2562 case glslang::EOpKill:
2563 builder.makeDiscard();
2564 break;
2565 case glslang::EOpBreak:
2566 if (breakForLoop.top())
2567 builder.createLoopExit();
2568 else
2569 builder.addSwitchBreak();
2570 break;
2571 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002572 builder.createLoopContinue();
2573 break;
2574 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002575 if (node->getExpression()) {
2576 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2577 spv::Id returnId = accessChainLoad(glslangReturnType);
2578 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2579 builder.clearAccessChain();
2580 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2581 builder.setAccessChainLValue(copyId);
2582 multiTypeStore(glslangReturnType, returnId);
2583 returnId = builder.createLoad(copyId);
2584 }
2585 builder.makeReturn(false, returnId);
2586 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002587 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002588
2589 builder.clearAccessChain();
2590 break;
2591
2592 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002593 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002594 break;
2595 }
2596
2597 return false;
2598}
2599
2600spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2601{
qining25262b32016-05-06 17:25:16 -04002602 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002603 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002604 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002605 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002606 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002607 }
2608
2609 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002610 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002611 spv::Id spvType = convertGlslangToSpvType(node->getType());
2612
Rex Xucabbb782017-03-24 13:41:14 +08002613 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2614 node->getType().containsBasicType(glslang::EbtInt16) ||
2615 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002616 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002617 switch (storageClass) {
2618 case spv::StorageClassInput:
2619 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002620 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002621 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002622 break;
2623 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002624 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002625 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002626 break;
2627 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002628 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002629 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2630 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002631 else
2632 builder.addCapability(spv::CapabilityStorageUniform16);
2633 break;
2634 case spv::StorageClassStorageBuffer:
2635 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2636 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2637 break;
2638 default:
2639 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002640 }
2641 }
Rex Xuf89ad982017-04-07 23:22:33 +08002642
John Kessenich312dcfb2018-07-03 13:19:51 -06002643 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2644 node->getType().containsBasicType(glslang::EbtUint8);
2645 if (contains8BitType) {
2646 if (storageClass == spv::StorageClassPushConstant) {
2647 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2648 builder.addCapability(spv::CapabilityStoragePushConstant8);
2649 } else if (storageClass == spv::StorageClassUniform) {
2650 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2651 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2652 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2653 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2654 }
2655 }
2656
John Kessenich140f3df2015-06-26 16:58:36 -06002657 const char* name = node->getName().c_str();
2658 if (glslang::IsAnonymous(name))
2659 name = "";
2660
2661 return builder.createVariable(storageClass, spvType, name);
2662}
2663
2664// Return type Id of the sampled type.
2665spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2666{
2667 switch (sampler.type) {
2668 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002669#ifdef AMD_EXTENSIONS
2670 case glslang::EbtFloat16:
2671 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2672 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2673 return builder.makeFloatType(16);
2674#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002675 case glslang::EbtInt: return builder.makeIntType(32);
2676 case glslang::EbtUint: return builder.makeUintType(32);
2677 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002678 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002679 return builder.makeFloatType(32);
2680 }
2681}
2682
John Kessenich8c8505c2016-07-26 12:50:38 -06002683// If node is a swizzle operation, return the type that should be used if
2684// the swizzle base is first consumed by another operation, before the swizzle
2685// is applied.
2686spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2687{
John Kessenichecba76f2017-01-06 00:34:48 -07002688 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002689 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2690 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2691 else
2692 return spv::NoType;
2693}
2694
2695// When inverting a swizzle with a parent op, this function
2696// will apply the swizzle operation to a completed parent operation.
2697spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2698{
2699 std::vector<unsigned> swizzle;
2700 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2701 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2702}
2703
John Kessenich8c8505c2016-07-26 12:50:38 -06002704// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2705void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2706{
2707 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2708 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2709 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2710}
2711
John Kessenich3ac051e2015-12-20 11:29:16 -07002712// Convert from a glslang type to an SPV type, by calling into a
2713// recursive version of this function. This establishes the inherited
2714// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002715spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2716{
John Kessenichead86222018-03-28 18:01:20 -06002717 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002718}
2719
2720// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002721// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002722// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002723spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2724 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002725{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002726 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002727
2728 switch (type.getBasicType()) {
2729 case glslang::EbtVoid:
2730 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002731 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002732 break;
2733 case glslang::EbtFloat:
2734 spvType = builder.makeFloatType(32);
2735 break;
2736 case glslang::EbtDouble:
2737 spvType = builder.makeFloatType(64);
2738 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002739 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002740 spvType = builder.makeFloatType(16);
2741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002743 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2744 // a 32-bit int where non-0 means true.
2745 if (explicitLayout != glslang::ElpNone)
2746 spvType = builder.makeUintType(32);
2747 else
2748 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002750 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002751 spvType = builder.makeIntType(8);
2752 break;
2753 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002754 spvType = builder.makeUintType(8);
2755 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002756 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002757 spvType = builder.makeIntType(16);
2758 break;
2759 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002760 spvType = builder.makeUintType(16);
2761 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002762 case glslang::EbtInt:
2763 spvType = builder.makeIntType(32);
2764 break;
2765 case glslang::EbtUint:
2766 spvType = builder.makeUintType(32);
2767 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002768 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002769 spvType = builder.makeIntType(64);
2770 break;
2771 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002772 spvType = builder.makeUintType(64);
2773 break;
John Kessenich426394d2015-07-23 10:22:48 -06002774 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002775 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002776 spvType = builder.makeUintType(32);
2777 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002778 case glslang::EbtSampler:
2779 {
2780 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002781 if (sampler.sampler) {
2782 // pure sampler
2783 spvType = builder.makeSamplerType();
2784 } else {
2785 // an image is present, make its type
2786 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2787 sampler.image ? 2 : 1, TranslateImageFormat(type));
2788 if (sampler.combined) {
2789 // already has both image and sampler, make the combined type
2790 spvType = builder.makeSampledImageType(spvType);
2791 }
John Kessenich55e7d112015-11-15 21:33:39 -07002792 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002793 }
John Kessenich140f3df2015-06-26 16:58:36 -06002794 break;
2795 case glslang::EbtStruct:
2796 case glslang::EbtBlock:
2797 {
2798 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002799 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002800
2801 // Try to share structs for different layouts, but not yet for other
2802 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002803 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002804 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002805 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002806 break;
2807
2808 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002809 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002810 memberRemapper[glslangMembers].resize(glslangMembers->size());
2811 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002812 }
2813 break;
2814 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002815 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002816 break;
2817 }
2818
2819 if (type.isMatrix())
2820 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2821 else {
2822 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2823 if (type.getVectorSize() > 1)
2824 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2825 }
2826
2827 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002828 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2829
John Kessenichc9a80832015-09-12 12:17:44 -06002830 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002831 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002832 // We need to decorate array strides for types needing explicit layout, except blocks.
2833 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002834 // Use a dummy glslang type for querying internal strides of
2835 // arrays of arrays, but using just a one-dimensional array.
2836 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002837 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2838 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002839
2840 // Will compute the higher-order strides here, rather than making a whole
2841 // pile of types and doing repetitive recursion on their contents.
2842 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2843 }
John Kessenichf8842e52016-01-04 19:22:56 -07002844
2845 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002846 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002847 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002848 if (stride > 0)
2849 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002850 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002851 }
2852 } else {
2853 // single-dimensional array, and don't yet have stride
2854
John Kessenichf8842e52016-01-04 19:22:56 -07002855 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002856 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2857 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002858 }
John Kessenich31ed4832015-09-09 17:51:38 -06002859
John Kessenichead86222018-03-28 18:01:20 -06002860 // Do the outer dimension, which might not be known for a runtime-sized array.
2861 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2862 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002863 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002864 else {
2865 if (!lastBufferBlockMember) {
2866 builder.addExtension("SPV_EXT_descriptor_indexing");
2867 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2868 }
John Kessenichead86222018-03-28 18:01:20 -06002869 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002870 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002871 if (stride > 0)
2872 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002873 }
2874
2875 return spvType;
2876}
2877
John Kessenich0e737842017-03-24 18:38:16 -06002878// TODO: this functionality should exist at a higher level, in creating the AST
2879//
2880// Identify interface members that don't have their required extension turned on.
2881//
2882bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2883{
2884 auto& extensions = glslangIntermediate->getRequestedExtensions();
2885
Rex Xubcf291a2017-03-29 23:01:36 +08002886 if (member.getFieldName() == "gl_ViewportMask" &&
2887 extensions.find("GL_NV_viewport_array2") == extensions.end())
2888 return true;
2889 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2890 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2891 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002892 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2893 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2894 return true;
2895 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2896 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2897 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002898 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2899 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2900 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002901
2902 return false;
2903};
2904
John Kessenich6090df02016-06-30 21:18:02 -06002905// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2906// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2907// Mutually recursive with convertGlslangToSpvType().
2908spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2909 const glslang::TTypeList* glslangMembers,
2910 glslang::TLayoutPacking explicitLayout,
2911 const glslang::TQualifier& qualifier)
2912{
2913 // Create a vector of struct types for SPIR-V to consume
2914 std::vector<spv::Id> spvMembers;
2915 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 -06002916 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2917 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2918 if (glslangMember.hiddenMember()) {
2919 ++memberDelta;
2920 if (type.getBasicType() == glslang::EbtBlock)
2921 memberRemapper[glslangMembers][i] = -1;
2922 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002923 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002924 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002925 if (filterMember(glslangMember))
2926 continue;
2927 }
John Kessenich6090df02016-06-30 21:18:02 -06002928 // modify just this child's view of the qualifier
2929 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2930 InheritQualifiers(memberQualifier, qualifier);
2931
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002932 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002933 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002934 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002935
2936 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002937 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2938 i == (int)glslangMembers->size() - 1;
2939 spvMembers.push_back(
2940 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002941 }
2942 }
2943
2944 // Make the SPIR-V type
2945 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002946 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002947 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2948
2949 // Decorate it
2950 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2951
2952 return spvType;
2953}
2954
2955void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2956 const glslang::TTypeList* glslangMembers,
2957 glslang::TLayoutPacking explicitLayout,
2958 const glslang::TQualifier& qualifier,
2959 spv::Id spvType)
2960{
2961 // Name and decorate the non-hidden members
2962 int offset = -1;
2963 int locationOffset = 0; // for use within the members of this struct
2964 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2965 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2966 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002967 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002968 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002969 if (filterMember(glslangMember))
2970 continue;
2971 }
John Kessenich6090df02016-06-30 21:18:02 -06002972
2973 // modify just this child's view of the qualifier
2974 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2975 InheritQualifiers(memberQualifier, qualifier);
2976
2977 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002978 if (member < 0)
2979 continue;
2980
2981 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2982 builder.addMemberDecoration(spvType, member,
2983 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2984 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2985 // Add interpolation and auxiliary storage decorations only to
2986 // top-level members of Input and Output storage classes
2987 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2988 type.getQualifier().storage == glslang::EvqVaryingOut) {
2989 if (type.getBasicType() == glslang::EbtBlock ||
2990 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2991 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2992 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002993 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002994 }
2995 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002996
John Kessenich5d610ee2018-03-07 18:05:55 -07002997 if (type.getBasicType() == glslang::EbtBlock &&
2998 qualifier.storage == glslang::EvqBuffer) {
2999 // Add memory decorations only to top-level members of shader storage block
3000 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003001 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003002 for (unsigned int i = 0; i < memory.size(); ++i)
3003 builder.addMemberDecoration(spvType, member, memory[i]);
3004 }
John Kessenich6090df02016-06-30 21:18:02 -06003005
John Kessenich5d610ee2018-03-07 18:05:55 -07003006 // Location assignment was already completed correctly by the front end,
3007 // just track whether a member needs to be decorated.
3008 // Ignore member locations if the container is an array, as that's
3009 // ill-specified and decisions have been made to not allow this.
3010 if (! type.isArray() && memberQualifier.hasLocation())
3011 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003012
John Kessenich5d610ee2018-03-07 18:05:55 -07003013 if (qualifier.hasLocation()) // track for upcoming inheritance
3014 locationOffset += glslangIntermediate->computeTypeLocationSize(
3015 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003016
John Kessenich5d610ee2018-03-07 18:05:55 -07003017 // component, XFB, others
3018 if (glslangMember.getQualifier().hasComponent())
3019 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3020 glslangMember.getQualifier().layoutComponent);
3021 if (glslangMember.getQualifier().hasXfbOffset())
3022 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3023 glslangMember.getQualifier().layoutXfbOffset);
3024 else if (explicitLayout != glslang::ElpNone) {
3025 // figure out what to do with offset, which is accumulating
3026 int nextOffset;
3027 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3028 if (offset >= 0)
3029 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3030 offset = nextOffset;
3031 }
John Kessenich6090df02016-06-30 21:18:02 -06003032
John Kessenich5d610ee2018-03-07 18:05:55 -07003033 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3034 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3035 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003036
John Kessenich5d610ee2018-03-07 18:05:55 -07003037 // built-in variable decorations
3038 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3039 if (builtIn != spv::BuiltInMax)
3040 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003041
John Kessenich5611c6d2018-04-05 11:25:02 -06003042 // nonuniform
3043 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3044
John Kessenichead86222018-03-28 18:01:20 -06003045 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3046 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3047 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3048 memberQualifier.semanticName);
3049 }
3050
chaoc771d89f2017-01-13 01:10:53 -08003051#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003052 if (builtIn == spv::BuiltInLayer) {
3053 // SPV_NV_viewport_array2 extension
3054 if (glslangMember.getQualifier().layoutViewportRelative){
3055 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3056 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3057 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003058 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003059 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3060 builder.addMemberDecoration(spvType, member,
3061 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3062 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3063 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3064 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003065 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003066 }
3067 if (glslangMember.getQualifier().layoutPassthrough) {
3068 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3069 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3070 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3071 }
chaoc771d89f2017-01-13 01:10:53 -08003072#endif
John Kessenich6090df02016-06-30 21:18:02 -06003073 }
3074
3075 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003076 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3077 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003078 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3079 builder.addCapability(spv::CapabilityGeometryStreams);
3080 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3081 }
John Kessenich6090df02016-06-30 21:18:02 -06003082}
3083
John Kessenich6c292d32016-02-15 20:58:50 -07003084// Turn the expression forming the array size into an id.
3085// This is not quite trivial, because of specialization constants.
3086// Sometimes, a raw constant is turned into an Id, and sometimes
3087// a specialization constant expression is.
3088spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3089{
3090 // First, see if this is sized with a node, meaning a specialization constant:
3091 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3092 if (specNode != nullptr) {
3093 builder.clearAccessChain();
3094 specNode->traverse(this);
3095 return accessChainLoad(specNode->getAsTyped()->getType());
3096 }
qining25262b32016-05-06 17:25:16 -04003097
John Kessenich6c292d32016-02-15 20:58:50 -07003098 // Otherwise, need a compile-time (front end) size, get it:
3099 int size = arraySizes.getDimSize(dim);
3100 assert(size > 0);
3101 return builder.makeUintConstant(size);
3102}
3103
John Kessenich103bef92016-02-08 21:38:15 -07003104// Wrap the builder's accessChainLoad to:
3105// - localize handling of RelaxedPrecision
3106// - use the SPIR-V inferred type instead of another conversion of the glslang type
3107// (avoids unnecessary work and possible type punning for structures)
3108// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003109spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3110{
John Kessenich103bef92016-02-08 21:38:15 -07003111 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003112
3113 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3114 coherentFlags |= TranslateCoherent(type);
3115
John Kessenich5611c6d2018-04-05 11:25:02 -06003116 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003117 TranslateNonUniformDecoration(type.getQualifier()),
3118 nominalTypeId,
3119 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3120 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003121
3122 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003123 if (type.getBasicType() == glslang::EbtBool) {
3124 if (builder.isScalarType(nominalTypeId)) {
3125 // Conversion for bool
3126 spv::Id boolType = builder.makeBoolType();
3127 if (nominalTypeId != boolType)
3128 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3129 } else if (builder.isVectorType(nominalTypeId)) {
3130 // Conversion for bvec
3131 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3132 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3133 if (nominalTypeId != bvecType)
3134 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3135 }
3136 }
John Kessenich103bef92016-02-08 21:38:15 -07003137
3138 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003139}
3140
Rex Xu27253232016-02-23 17:51:09 +08003141// Wrap the builder's accessChainStore to:
3142// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003143//
3144// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003145void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3146{
3147 // Need to convert to abstract types when necessary
3148 if (type.getBasicType() == glslang::EbtBool) {
3149 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3150
3151 if (builder.isScalarType(nominalTypeId)) {
3152 // Conversion for bool
3153 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003154 if (nominalTypeId != boolType) {
3155 // keep these outside arguments, for determinant order-of-evaluation
3156 spv::Id one = builder.makeUintConstant(1);
3157 spv::Id zero = builder.makeUintConstant(0);
3158 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3159 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003160 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003161 } else if (builder.isVectorType(nominalTypeId)) {
3162 // Conversion for bvec
3163 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3164 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003165 if (nominalTypeId != bvecType) {
3166 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003167 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3168 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3169 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003170 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003171 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3172 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003173 }
3174 }
3175
Jeff Bolz36831c92018-09-05 10:11:41 -05003176 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3177 coherentFlags |= TranslateCoherent(type);
3178
3179 builder.accessChainStore(rvalue,
3180 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3181 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003182}
3183
John Kessenich4bf71552016-09-02 11:20:21 -06003184// For storing when types match at the glslang level, but not might match at the
3185// SPIR-V level.
3186//
3187// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003188// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003189// as in a member-decorated way.
3190//
3191// NOTE: This function can handle any store request; if it's not special it
3192// simplifies to a simple OpStore.
3193//
3194// Implicitly uses the existing builder.accessChain as the storage target.
3195void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3196{
John Kessenichb3e24e42016-09-11 12:33:43 -06003197 // we only do the complex path here if it's an aggregate
3198 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003199 accessChainStore(type, rValue);
3200 return;
3201 }
3202
John Kessenichb3e24e42016-09-11 12:33:43 -06003203 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003204 spv::Id rType = builder.getTypeId(rValue);
3205 spv::Id lValue = builder.accessChainGetLValue();
3206 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3207 if (lType == rType) {
3208 accessChainStore(type, rValue);
3209 return;
3210 }
3211
John Kessenichb3e24e42016-09-11 12:33:43 -06003212 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003213 // where the two types were the same type in GLSL. This requires member
3214 // by member copy, recursively.
3215
John Kessenichb3e24e42016-09-11 12:33:43 -06003216 // If an array, copy element by element.
3217 if (type.isArray()) {
3218 glslang::TType glslangElementType(type, 0);
3219 spv::Id elementRType = builder.getContainedTypeId(rType);
3220 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3221 // get the source member
3222 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003223
John Kessenichb3e24e42016-09-11 12:33:43 -06003224 // set up the target storage
3225 builder.clearAccessChain();
3226 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003227 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003228
John Kessenichb3e24e42016-09-11 12:33:43 -06003229 // store the member
3230 multiTypeStore(glslangElementType, elementRValue);
3231 }
3232 } else {
3233 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003234
John Kessenichb3e24e42016-09-11 12:33:43 -06003235 // loop over structure members
3236 const glslang::TTypeList& members = *type.getStruct();
3237 for (int m = 0; m < (int)members.size(); ++m) {
3238 const glslang::TType& glslangMemberType = *members[m].type;
3239
3240 // get the source member
3241 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3242 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3243
3244 // set up the target storage
3245 builder.clearAccessChain();
3246 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003247 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003248
3249 // store the member
3250 multiTypeStore(glslangMemberType, memberRValue);
3251 }
John Kessenich4bf71552016-09-02 11:20:21 -06003252 }
3253}
3254
John Kessenichf85e8062015-12-19 13:57:10 -07003255// Decide whether or not this type should be
3256// decorated with offsets and strides, and if so
3257// whether std140 or std430 rules should be applied.
3258glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003259{
John Kessenichf85e8062015-12-19 13:57:10 -07003260 // has to be a block
3261 if (type.getBasicType() != glslang::EbtBlock)
3262 return glslang::ElpNone;
3263
3264 // has to be a uniform or buffer block
3265 if (type.getQualifier().storage != glslang::EvqUniform &&
3266 type.getQualifier().storage != glslang::EvqBuffer)
3267 return glslang::ElpNone;
3268
3269 // return the layout to use
3270 switch (type.getQualifier().layoutPacking) {
3271 case glslang::ElpStd140:
3272 case glslang::ElpStd430:
3273 return type.getQualifier().layoutPacking;
3274 default:
3275 return glslang::ElpNone;
3276 }
John Kessenich31ed4832015-09-09 17:51:38 -06003277}
3278
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003279// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003280int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003281{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003282 int size;
John Kessenich49987892015-12-29 17:11:44 -07003283 int stride;
3284 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003285
3286 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003287}
3288
John Kessenich49987892015-12-29 17:11:44 -07003289// 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 -07003290// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003291int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003292{
John Kessenich49987892015-12-29 17:11:44 -07003293 glslang::TType elementType;
3294 elementType.shallowCopy(matrixType);
3295 elementType.clearArraySizes();
3296
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003297 int size;
John Kessenich49987892015-12-29 17:11:44 -07003298 int stride;
3299 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3300
3301 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003302}
3303
John Kessenich5e4b1242015-08-06 22:53:06 -06003304// Given a member type of a struct, realign the current offset for it, and compute
3305// the next (not yet aligned) offset for the next member, which will get aligned
3306// on the next call.
3307// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3308// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3309// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003310void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003311 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003312{
3313 // this will get a positive value when deemed necessary
3314 nextOffset = -1;
3315
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 // override anything in currentOffset with user-set offset
3317 if (memberType.getQualifier().hasOffset())
3318 currentOffset = memberType.getQualifier().layoutOffset;
3319
3320 // It could be that current linker usage in glslang updated all the layoutOffset,
3321 // in which case the following code does not matter. But, that's not quite right
3322 // once cross-compilation unit GLSL validation is done, as the original user
3323 // settings are needed in layoutOffset, and then the following will come into play.
3324
John Kessenichf85e8062015-12-19 13:57:10 -07003325 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003326 if (! memberType.getQualifier().hasOffset())
3327 currentOffset = -1;
3328
3329 return;
3330 }
3331
John Kessenichf85e8062015-12-19 13:57:10 -07003332 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003333 if (currentOffset < 0)
3334 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003335
John Kessenich5e4b1242015-08-06 22:53:06 -06003336 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3337 // but possibly not yet correctly aligned.
3338
3339 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003340 int dummyStride;
3341 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003342
3343 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003344 // TODO: make this consistent in early phases of code:
3345 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3346 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3347 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003348 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003349 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003350 int dummySize;
3351 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3352 if (componentAlignment <= 4)
3353 memberAlignment = componentAlignment;
3354 }
3355
3356 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003357 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003358
3359 // Bump up to vec4 if there is a bad straddle
3360 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3361 glslang::RoundToPow2(currentOffset, 16);
3362
John Kessenich5e4b1242015-08-06 22:53:06 -06003363 nextOffset = currentOffset + memberSize;
3364}
3365
David Netoa901ffe2016-06-08 14:11:40 +01003366void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003367{
David Netoa901ffe2016-06-08 14:11:40 +01003368 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3369 switch (glslangBuiltIn)
3370 {
3371 case glslang::EbvClipDistance:
3372 case glslang::EbvCullDistance:
3373 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003374#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003375 case glslang::EbvViewportMaskNV:
3376 case glslang::EbvSecondaryPositionNV:
3377 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003378 case glslang::EbvPositionPerViewNV:
3379 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003380#endif
David Netoa901ffe2016-06-08 14:11:40 +01003381 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3382 // Alternately, we could just call this for any glslang built-in, since the
3383 // capability already guards against duplicates.
3384 TranslateBuiltInDecoration(glslangBuiltIn, false);
3385 break;
3386 default:
3387 // Capabilities were already generated when the struct was declared.
3388 break;
3389 }
John Kessenichebb50532016-05-16 19:22:05 -06003390}
3391
John Kessenich6fccb3c2016-09-19 16:01:41 -06003392bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003393{
John Kessenicheee9d532016-09-19 18:09:30 -06003394 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003395}
3396
John Kessenichd41993d2017-09-10 15:21:05 -06003397// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003398// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3399// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003400bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003401{
John Kessenich6a14f782017-12-04 02:48:10 -07003402 assert(qualifier == glslang::EvqIn ||
3403 qualifier == glslang::EvqOut ||
3404 qualifier == glslang::EvqInOut ||
3405 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003406 return qualifier != glslang::EvqConstReadOnly;
3407}
3408
3409// Is parameter pass-by-original?
3410bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3411 bool implicitThisParam)
3412{
3413 if (implicitThisParam) // implicit this
3414 return true;
3415 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003416 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003417 return paramType.containsOpaque() || // sampler, etc.
3418 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3419}
3420
John Kessenich140f3df2015-06-26 16:58:36 -06003421// Make all the functions, skeletally, without actually visiting their bodies.
3422void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3423{
Jeff Bolz36831c92018-09-05 10:11:41 -05003424 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003425 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3426 if (paramPrecision != spv::NoPrecision)
3427 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003428 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003429 };
3430
John Kessenich140f3df2015-06-26 16:58:36 -06003431 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3432 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003433 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003434 continue;
3435
3436 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003437 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003438 //
qining25262b32016-05-06 17:25:16 -04003439 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003440 // function. What it is an address of varies:
3441 //
John Kessenich4bf71552016-09-02 11:20:21 -06003442 // - "in" parameters not marked as "const" can be written to without modifying the calling
3443 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003444 //
3445 // - "const in" parameters can just be the r-value, as no writes need occur.
3446 //
John Kessenich4bf71552016-09-02 11:20:21 -06003447 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3448 // 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 -06003449
3450 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003451 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003452 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3453
John Kessenichfad62972017-07-18 02:35:46 -06003454 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3455 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003456
John Kessenichfad62972017-07-18 02:35:46 -06003457 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003458 for (int p = 0; p < (int)parameters.size(); ++p) {
3459 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3460 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003461 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003462 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003463 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003464 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3465 else
John Kessenich4bf71552016-09-02 11:20:21 -06003466 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003467 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003468 paramTypes.push_back(typeId);
3469 }
3470
3471 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003472 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3473 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003474 glslFunction->getName().c_str(), paramTypes,
3475 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003476 if (implicitThis)
3477 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003478
3479 // Track function to emit/call later
3480 functionMap[glslFunction->getName().c_str()] = function;
3481
3482 // Set the parameter id's
3483 for (int p = 0; p < (int)parameters.size(); ++p) {
3484 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3485 // give a name too
3486 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3487 }
3488 }
3489}
3490
3491// Process all the initializers, while skipping the functions and link objects
3492void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3493{
3494 builder.setBuildPoint(shaderEntry->getLastBlock());
3495 for (int i = 0; i < (int)initializers.size(); ++i) {
3496 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3497 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3498
3499 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003500 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003501 initializer->traverse(this);
3502 }
3503 }
3504}
3505
3506// Process all the functions, while skipping initializers.
3507void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3508{
3509 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3510 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003511 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003512 node->traverse(this);
3513 }
3514}
3515
3516void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3517{
qining25262b32016-05-06 17:25:16 -04003518 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003519 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003520 currentFunction = functionMap[node->getName().c_str()];
3521 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003522 builder.setBuildPoint(functionBlock);
3523}
3524
Rex Xu04db3f52015-09-16 11:44:02 +08003525void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003526{
Rex Xufc618912015-09-09 16:42:49 +08003527 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003528
3529 glslang::TSampler sampler = {};
3530 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003531#ifdef AMD_EXTENSIONS
3532 bool f16ShadowCompare = false;
3533#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003534 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003535 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3536 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003537#ifdef AMD_EXTENSIONS
3538 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3539#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003540 }
3541
John Kessenich140f3df2015-06-26 16:58:36 -06003542 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3543 builder.clearAccessChain();
3544 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003545
3546 // Special case l-value operands
3547 bool lvalue = false;
3548 switch (node.getOp()) {
3549 case glslang::EOpImageAtomicAdd:
3550 case glslang::EOpImageAtomicMin:
3551 case glslang::EOpImageAtomicMax:
3552 case glslang::EOpImageAtomicAnd:
3553 case glslang::EOpImageAtomicOr:
3554 case glslang::EOpImageAtomicXor:
3555 case glslang::EOpImageAtomicExchange:
3556 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003557 case glslang::EOpImageAtomicLoad:
3558 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003559 if (i == 0)
3560 lvalue = true;
3561 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003562 case glslang::EOpSparseImageLoad:
3563 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3564 lvalue = true;
3565 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003566#ifdef AMD_EXTENSIONS
3567 case glslang::EOpSparseTexture:
3568 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3569 lvalue = true;
3570 break;
3571 case glslang::EOpSparseTextureClamp:
3572 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3573 lvalue = true;
3574 break;
3575 case glslang::EOpSparseTextureLod:
3576 case glslang::EOpSparseTextureOffset:
3577 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3578 lvalue = true;
3579 break;
3580#else
Rex Xu48edadf2015-12-31 16:11:41 +08003581 case glslang::EOpSparseTexture:
3582 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3583 lvalue = true;
3584 break;
3585 case glslang::EOpSparseTextureClamp:
3586 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3587 lvalue = true;
3588 break;
3589 case glslang::EOpSparseTextureLod:
3590 case glslang::EOpSparseTextureOffset:
3591 if (i == 3)
3592 lvalue = true;
3593 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003594#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003595 case glslang::EOpSparseTextureFetch:
3596 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3597 lvalue = true;
3598 break;
3599 case glslang::EOpSparseTextureFetchOffset:
3600 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3601 lvalue = true;
3602 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003603#ifdef AMD_EXTENSIONS
3604 case glslang::EOpSparseTextureLodOffset:
3605 case glslang::EOpSparseTextureGrad:
3606 case glslang::EOpSparseTextureOffsetClamp:
3607 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3608 lvalue = true;
3609 break;
3610 case glslang::EOpSparseTextureGradOffset:
3611 case glslang::EOpSparseTextureGradClamp:
3612 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3613 lvalue = true;
3614 break;
3615 case glslang::EOpSparseTextureGradOffsetClamp:
3616 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3617 lvalue = true;
3618 break;
3619#else
Rex Xu48edadf2015-12-31 16:11:41 +08003620 case glslang::EOpSparseTextureLodOffset:
3621 case glslang::EOpSparseTextureGrad:
3622 case glslang::EOpSparseTextureOffsetClamp:
3623 if (i == 4)
3624 lvalue = true;
3625 break;
3626 case glslang::EOpSparseTextureGradOffset:
3627 case glslang::EOpSparseTextureGradClamp:
3628 if (i == 5)
3629 lvalue = true;
3630 break;
3631 case glslang::EOpSparseTextureGradOffsetClamp:
3632 if (i == 6)
3633 lvalue = true;
3634 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003635#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003636 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003637 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3638 lvalue = true;
3639 break;
3640 case glslang::EOpSparseTextureGatherOffset:
3641 case glslang::EOpSparseTextureGatherOffsets:
3642 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3643 lvalue = true;
3644 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003645#ifdef AMD_EXTENSIONS
3646 case glslang::EOpSparseTextureGatherLod:
3647 if (i == 3)
3648 lvalue = true;
3649 break;
3650 case glslang::EOpSparseTextureGatherLodOffset:
3651 case glslang::EOpSparseTextureGatherLodOffsets:
3652 if (i == 4)
3653 lvalue = true;
3654 break;
Rex Xu129799a2017-07-05 17:23:28 +08003655 case glslang::EOpSparseImageLoadLod:
3656 if (i == 3)
3657 lvalue = true;
3658 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003659#endif
Rex Xufc618912015-09-09 16:42:49 +08003660 default:
3661 break;
3662 }
3663
Rex Xu6b86d492015-09-16 17:48:22 +08003664 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003665 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003666 else
John Kessenich32cfd492016-02-02 12:37:46 -07003667 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003668 }
3669}
3670
John Kessenichfc51d282015-08-19 13:34:18 -06003671void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003672{
John Kessenichfc51d282015-08-19 13:34:18 -06003673 builder.clearAccessChain();
3674 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003675 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003676}
John Kessenich140f3df2015-06-26 16:58:36 -06003677
John Kessenichfc51d282015-08-19 13:34:18 -06003678spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3679{
John Kesseniche485c7a2017-05-31 18:50:53 -06003680 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003681 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003682
3683 builder.setLine(node->getLoc().line);
3684
John Kessenichfc51d282015-08-19 13:34:18 -06003685 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003686
3687 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3688 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3689 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003690#ifdef AMD_EXTENSIONS
3691 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3692 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3693 : false;
3694#endif
3695
John Kessenichfc51d282015-08-19 13:34:18 -06003696 std::vector<spv::Id> arguments;
3697 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003698 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003699 else
3700 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003701 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003702
3703 spv::Builder::TextureParameters params = { };
3704 params.sampler = arguments[0];
3705
Rex Xu04db3f52015-09-16 11:44:02 +08003706 glslang::TCrackedTextureOp cracked;
3707 node->crackTexture(sampler, cracked);
3708
amhagan05506bb2017-06-13 16:53:02 -04003709 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003710
John Kessenichfc51d282015-08-19 13:34:18 -06003711 // Check for queries
3712 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003713 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3714 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003715 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003716
John Kessenichfc51d282015-08-19 13:34:18 -06003717 switch (node->getOp()) {
3718 case glslang::EOpImageQuerySize:
3719 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003720 if (arguments.size() > 1) {
3721 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003722 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003723 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003724 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003725 case glslang::EOpImageQuerySamples:
3726 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003727 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003728 case glslang::EOpTextureQueryLod:
3729 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003730 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003731 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003732 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003733 case glslang::EOpSparseTexelsResident:
3734 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003735 default:
3736 assert(0);
3737 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 }
John Kessenich140f3df2015-06-26 16:58:36 -06003739 }
3740
LoopDawg4425f242018-02-18 11:40:01 -07003741 int components = node->getType().getVectorSize();
3742
3743 if (node->getOp() == glslang::EOpTextureFetch) {
3744 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3745 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3746 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3747 // here around e.g. which ones return scalars or other types.
3748 components = 4;
3749 }
3750
3751 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3752
3753 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3754
Rex Xufc618912015-09-09 16:42:49 +08003755 // Check for image functions other than queries
3756 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003757 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003758 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003759 spv::IdImmediate image = { true, *(opIt++) };
3760 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003761
3762 // Handle subpass operations
3763 // TODO: GLSL should change to have the "MS" only on the type rather than the
3764 // built-in function.
3765 if (cracked.subpass) {
3766 // add on the (0,0) coordinate
3767 spv::Id zero = builder.makeIntConstant(0);
3768 std::vector<spv::Id> comps;
3769 comps.push_back(zero);
3770 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003771 spv::IdImmediate coord = { true,
3772 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3773 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003774 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003775 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3776 operands.push_back(imageOperands);
3777 spv::IdImmediate imageOperand = { true, *(opIt++) };
3778 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003779 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003780 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3781 builder.setPrecision(result, precision);
3782 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003783 }
3784
John Kessenich149afc32018-08-14 13:31:43 -06003785 spv::IdImmediate coord = { true, *(opIt++) };
3786 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003787#ifdef AMD_EXTENSIONS
3788 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3789#else
John Kessenich56bab042015-09-16 10:54:31 -06003790 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003791#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003792 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003793 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003794 mask = mask | spv::ImageOperandsSampleMask;
3795 }
Rex Xu129799a2017-07-05 17:23:28 +08003796#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003797 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003798 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3799 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003800 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003801 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003802#endif
3803 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3804 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3805 if (mask) {
3806 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3807 operands.push_back(imageOperands);
3808 }
3809 if (mask & spv::ImageOperandsSampleMask) {
3810 spv::IdImmediate imageOperand = { true, *opIt++ };
3811 operands.push_back(imageOperand);
3812 }
3813#ifdef AMD_EXTENSIONS
3814 if (mask & spv::ImageOperandsLodMask) {
3815 spv::IdImmediate imageOperand = { true, *opIt++ };
3816 operands.push_back(imageOperand);
3817 }
3818#endif
3819 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3820 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3821 operands.push_back(imageOperand);
3822 }
3823
John Kessenich149afc32018-08-14 13:31:43 -06003824 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003825 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003826
John Kessenich149afc32018-08-14 13:31:43 -06003827 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003828 builder.setPrecision(result[0], precision);
3829
3830 // If needed, add a conversion constructor to the proper size.
3831 if (components != node->getType().getVectorSize())
3832 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3833
3834 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003835#ifdef AMD_EXTENSIONS
3836 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3837#else
John Kessenich56bab042015-09-16 10:54:31 -06003838 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003839#endif
Rex Xu129799a2017-07-05 17:23:28 +08003840
Jeff Bolz36831c92018-09-05 10:11:41 -05003841 // Push the texel value before the operands
3842#ifdef AMD_EXTENSIONS
3843 if (sampler.ms || cracked.lod) {
3844#else
3845 if (sampler.ms) {
3846#endif
John Kessenich149afc32018-08-14 13:31:43 -06003847 spv::IdImmediate texel = { true, *(opIt + 1) };
3848 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003849 } else {
3850 spv::IdImmediate texel = { true, *opIt };
3851 operands.push_back(texel);
3852 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003853
3854 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3855 if (sampler.ms) {
3856 mask = mask | spv::ImageOperandsSampleMask;
3857 }
3858#ifdef AMD_EXTENSIONS
3859 if (cracked.lod) {
3860 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3861 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3862 mask = mask | spv::ImageOperandsLodMask;
3863 }
3864#endif
3865 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3866 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3867 if (mask) {
3868 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3869 operands.push_back(imageOperands);
3870 }
3871 if (mask & spv::ImageOperandsSampleMask) {
3872 spv::IdImmediate imageOperand = { true, *opIt++ };
3873 operands.push_back(imageOperand);
3874 }
3875#ifdef AMD_EXTENSIONS
3876 if (mask & spv::ImageOperandsLodMask) {
3877 spv::IdImmediate imageOperand = { true, *opIt++ };
3878 operands.push_back(imageOperand);
3879 }
3880#endif
3881 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
3882 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3883 operands.push_back(imageOperand);
3884 }
3885
John Kessenich56bab042015-09-16 10:54:31 -06003886 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003887 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003888 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003889 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003890#ifdef AMD_EXTENSIONS
3891 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3892#else
Rex Xu5eafa472016-02-19 22:24:03 +08003893 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003894#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003895 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003896 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003897 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3898
Jeff Bolz36831c92018-09-05 10:11:41 -05003899 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08003900 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003901 mask = mask | spv::ImageOperandsSampleMask;
3902 }
Rex Xu129799a2017-07-05 17:23:28 +08003903#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003904 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003905 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3906 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3907
Jeff Bolz36831c92018-09-05 10:11:41 -05003908 mask = mask | spv::ImageOperandsLodMask;
3909 }
3910#endif
3911 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3912 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3913 if (mask) {
3914 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06003915 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05003916 }
3917 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06003918 spv::IdImmediate imageOperand = { true, *opIt++ };
3919 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05003920 }
3921#ifdef AMD_EXTENSIONS
3922 if (mask & spv::ImageOperandsLodMask) {
3923 spv::IdImmediate imageOperand = { true, *opIt++ };
3924 operands.push_back(imageOperand);
3925 }
Rex Xu129799a2017-07-05 17:23:28 +08003926#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003927 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3928 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3929 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08003930 }
3931
3932 // Create the return type that was a special structure
3933 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003934 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003935 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3936 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3937
3938 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3939
3940 // Decode the return type
3941 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3942 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003943 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003944 // Process image atomic operations
3945
3946 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3947 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003948 // For non-MS, the sample value should be 0
3949 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3950 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003951
Jeff Bolz36831c92018-09-05 10:11:41 -05003952 spv::Id resultTypeId;
3953 // imageAtomicStore has a void return type so base the pointer type on
3954 // the type of the value operand.
3955 if (node->getOp() == glslang::EOpImageAtomicStore) {
3956 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
3957 } else {
3958 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
3959 }
John Kessenich56bab042015-09-16 10:54:31 -06003960 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003961
3962 std::vector<spv::Id> operands;
3963 operands.push_back(pointer);
3964 for (; opIt != arguments.end(); ++opIt)
3965 operands.push_back(*opIt);
3966
John Kessenich8c8505c2016-07-26 12:50:38 -06003967 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003968 }
3969 }
3970
amhagan05506bb2017-06-13 16:53:02 -04003971#ifdef AMD_EXTENSIONS
3972 // Check for fragment mask functions other than queries
3973 if (cracked.fragMask) {
3974 assert(sampler.ms);
3975
3976 auto opIt = arguments.begin();
3977 std::vector<spv::Id> operands;
3978
3979 // Extract the image if necessary
3980 if (builder.isSampledImage(params.sampler))
3981 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3982
3983 operands.push_back(params.sampler);
3984 ++opIt;
3985
3986 if (sampler.isSubpass()) {
3987 // add on the (0,0) coordinate
3988 spv::Id zero = builder.makeIntConstant(0);
3989 std::vector<spv::Id> comps;
3990 comps.push_back(zero);
3991 comps.push_back(zero);
3992 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3993 }
3994
3995 for (; opIt != arguments.end(); ++opIt)
3996 operands.push_back(*opIt);
3997
3998 spv::Op fragMaskOp = spv::OpNop;
3999 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4000 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4001 else if (node->getOp() == glslang::EOpFragmentFetch)
4002 fragMaskOp = spv::OpFragmentFetchAMD;
4003
4004 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4005 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4006 return builder.createOp(fragMaskOp, resultType(), operands);
4007 }
4008#endif
4009
Rex Xufc618912015-09-09 16:42:49 +08004010 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004011 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08004012 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4013
John Kessenichfc51d282015-08-19 13:34:18 -06004014 // check for bias argument
4015 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004016#ifdef AMD_EXTENSIONS
4017 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4018#else
Rex Xu71519fe2015-11-11 15:35:47 +08004019 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004020#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004021 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004022#ifdef AMD_EXTENSIONS
4023 if (cracked.gather)
4024 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004025
4026 if (f16ShadowCompare)
4027 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004028#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004029 if (cracked.offset)
4030 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004031#ifdef AMD_EXTENSIONS
4032 else if (cracked.offsets)
4033 ++nonBiasArgCount;
4034#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004035 if (cracked.grad)
4036 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004037 if (cracked.lodClamp)
4038 ++nonBiasArgCount;
4039 if (sparse)
4040 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004041
4042 if ((int)arguments.size() > nonBiasArgCount)
4043 bias = true;
4044 }
4045
John Kessenicha5c33d62016-06-02 23:45:21 -06004046 // See if the sampler param should really be just the SPV image part
4047 if (cracked.fetch) {
4048 // a fetch needs to have the image extracted first
4049 if (builder.isSampledImage(params.sampler))
4050 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4051 }
4052
Rex Xu225e0fc2016-11-17 17:47:59 +08004053#ifdef AMD_EXTENSIONS
4054 if (cracked.gather) {
4055 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4056 if (bias || cracked.lod ||
4057 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4058 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004059 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004060 }
4061 }
4062#endif
4063
John Kessenichfc51d282015-08-19 13:34:18 -06004064 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004065
John Kessenichfc51d282015-08-19 13:34:18 -06004066 params.coords = arguments[1];
4067 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004068 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004069
4070 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004071#ifdef AMD_EXTENSIONS
4072 if (cubeCompare || f16ShadowCompare) {
4073#else
Rex Xu48edadf2015-12-31 16:11:41 +08004074 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004075#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004076 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004077 ++extraArgs;
4078 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004079 params.Dref = arguments[2];
4080 ++extraArgs;
4081 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004082 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004083 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004084 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004085 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004086 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004087 dRefComp = builder.getNumComponents(params.coords) - 1;
4088 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004089 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4090 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004091
4092 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004093 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004094 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004095 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07004096 } else if (glslangIntermediate->getStage() != EShLangFragment) {
4097 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4098 noImplicitLod = true;
4099 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004100
4101 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004102 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004103 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004104 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004105 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004106
4107 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004108 if (cracked.grad) {
4109 params.gradX = arguments[2 + extraArgs];
4110 params.gradY = arguments[3 + extraArgs];
4111 extraArgs += 2;
4112 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004113
4114 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004115 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004116 params.offset = arguments[2 + extraArgs];
4117 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004118 } else if (cracked.offsets) {
4119 params.offsets = arguments[2 + extraArgs];
4120 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004121 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004122
4123 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004124 if (cracked.lodClamp) {
4125 params.lodClamp = arguments[2 + extraArgs];
4126 ++extraArgs;
4127 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004128
4129 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004130 if (sparse) {
4131 params.texelOut = arguments[2 + extraArgs];
4132 ++extraArgs;
4133 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004134
John Kessenich76d4dfc2016-06-16 12:43:23 -06004135 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004136 if (cracked.gather && ! sampler.shadow) {
4137 // default component is 0, if missing, otherwise an argument
4138 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004139 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004140 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004141 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004142 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004143 }
4144
4145 // bias
4146 if (bias) {
4147 params.bias = arguments[2 + extraArgs];
4148 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004149 }
John Kessenichfc51d282015-08-19 13:34:18 -06004150
John Kessenich65336482016-06-16 14:06:26 -06004151 // projective component (might not to move)
4152 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4153 // are divided by the last component of P."
4154 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4155 // unused components will appear after all used components."
4156 if (cracked.proj) {
4157 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4158 int projTargetComp;
4159 switch (sampler.dim) {
4160 case glslang::Esd1D: projTargetComp = 1; break;
4161 case glslang::Esd2D: projTargetComp = 2; break;
4162 case glslang::EsdRect: projTargetComp = 2; break;
4163 default: projTargetComp = projSourceComp; break;
4164 }
4165 // copy the projective coordinate if we have to
4166 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004167 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004168 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4169 projSourceComp);
4170 params.coords = builder.createCompositeInsert(projComp, params.coords,
4171 builder.getTypeId(params.coords), projTargetComp);
4172 }
4173 }
4174
Jeff Bolz36831c92018-09-05 10:11:41 -05004175 // nonprivate
4176 if (imageType.getQualifier().nonprivate) {
4177 params.nonprivate = true;
4178 }
4179
4180 // volatile
4181 if (imageType.getQualifier().volatil) {
4182 params.volatil = true;
4183 }
4184
St0fFa1184dd2018-04-09 21:08:14 +02004185 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004186 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004187 );
LoopDawg4425f242018-02-18 11:40:01 -07004188
4189 if (components != node->getType().getVectorSize())
4190 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4191
4192 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004193}
4194
4195spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4196{
4197 // Grab the function's pointer from the previously created function
4198 spv::Function* function = functionMap[node->getName().c_str()];
4199 if (! function)
4200 return 0;
4201
4202 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4203 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4204
4205 // See comments in makeFunctions() for details about the semantics for parameter passing.
4206 //
4207 // These imply we need a four step process:
4208 // 1. Evaluate the arguments
4209 // 2. Allocate and make copies of in, out, and inout arguments
4210 // 3. Make the call
4211 // 4. Copy back the results
4212
John Kessenichd3ed90b2018-05-04 11:43:03 -06004213 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004214 std::vector<spv::Builder::AccessChain> lValues;
4215 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004216 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004217 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004218 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004219 // build l-value
4220 builder.clearAccessChain();
4221 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004222 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004223 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004224 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004225 // save l-value
4226 lValues.push_back(builder.getAccessChain());
4227 } else {
4228 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004229 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004230 }
4231 }
4232
4233 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4234 // copy the original into that space.
4235 //
4236 // Also, build up the list of actual arguments to pass in for the call
4237 int lValueCount = 0;
4238 int rValueCount = 0;
4239 std::vector<spv::Id> spvArgs;
4240 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4241 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004242 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004243 builder.setAccessChain(lValues[lValueCount]);
4244 arg = builder.accessChainGetLValue();
4245 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004246 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004247 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004248 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004249 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4250 // need to copy the input into output space
4251 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004252 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004253 builder.clearAccessChain();
4254 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004255 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004256 }
4257 ++lValueCount;
4258 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004259 // process r-value, which involves a copy for a type mismatch
4260 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4261 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4262 builder.clearAccessChain();
4263 builder.setAccessChainLValue(argCopy);
4264 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4265 arg = builder.createLoad(argCopy);
4266 } else
4267 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004268 ++rValueCount;
4269 }
4270 spvArgs.push_back(arg);
4271 }
4272
4273 // 3. Make the call.
4274 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004275 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004276
4277 // 4. Copy back out an "out" arguments.
4278 lValueCount = 0;
4279 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004280 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004281 ++lValueCount;
4282 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004283 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4284 spv::Id copy = builder.createLoad(spvArgs[a]);
4285 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004286 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004287 }
4288 ++lValueCount;
4289 }
4290 }
4291
4292 return result;
4293}
4294
4295// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004296spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004297 spv::Id typeId, spv::Id left, spv::Id right,
4298 glslang::TBasicType typeProxy, bool reduceComparison)
4299{
John Kessenich66011cb2018-03-06 16:12:04 -07004300 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4301 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004302 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004303
4304 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004305 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004306 bool comparison = false;
4307
4308 switch (op) {
4309 case glslang::EOpAdd:
4310 case glslang::EOpAddAssign:
4311 if (isFloat)
4312 binOp = spv::OpFAdd;
4313 else
4314 binOp = spv::OpIAdd;
4315 break;
4316 case glslang::EOpSub:
4317 case glslang::EOpSubAssign:
4318 if (isFloat)
4319 binOp = spv::OpFSub;
4320 else
4321 binOp = spv::OpISub;
4322 break;
4323 case glslang::EOpMul:
4324 case glslang::EOpMulAssign:
4325 if (isFloat)
4326 binOp = spv::OpFMul;
4327 else
4328 binOp = spv::OpIMul;
4329 break;
4330 case glslang::EOpVectorTimesScalar:
4331 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004332 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004333 if (builder.isVector(right))
4334 std::swap(left, right);
4335 assert(builder.isScalar(right));
4336 needMatchingVectors = false;
4337 binOp = spv::OpVectorTimesScalar;
4338 } else
4339 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004340 break;
4341 case glslang::EOpVectorTimesMatrix:
4342 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004343 binOp = spv::OpVectorTimesMatrix;
4344 break;
4345 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004346 binOp = spv::OpMatrixTimesVector;
4347 break;
4348 case glslang::EOpMatrixTimesScalar:
4349 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004350 binOp = spv::OpMatrixTimesScalar;
4351 break;
4352 case glslang::EOpMatrixTimesMatrix:
4353 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004354 binOp = spv::OpMatrixTimesMatrix;
4355 break;
4356 case glslang::EOpOuterProduct:
4357 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004358 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004359 break;
4360
4361 case glslang::EOpDiv:
4362 case glslang::EOpDivAssign:
4363 if (isFloat)
4364 binOp = spv::OpFDiv;
4365 else if (isUnsigned)
4366 binOp = spv::OpUDiv;
4367 else
4368 binOp = spv::OpSDiv;
4369 break;
4370 case glslang::EOpMod:
4371 case glslang::EOpModAssign:
4372 if (isFloat)
4373 binOp = spv::OpFMod;
4374 else if (isUnsigned)
4375 binOp = spv::OpUMod;
4376 else
4377 binOp = spv::OpSMod;
4378 break;
4379 case glslang::EOpRightShift:
4380 case glslang::EOpRightShiftAssign:
4381 if (isUnsigned)
4382 binOp = spv::OpShiftRightLogical;
4383 else
4384 binOp = spv::OpShiftRightArithmetic;
4385 break;
4386 case glslang::EOpLeftShift:
4387 case glslang::EOpLeftShiftAssign:
4388 binOp = spv::OpShiftLeftLogical;
4389 break;
4390 case glslang::EOpAnd:
4391 case glslang::EOpAndAssign:
4392 binOp = spv::OpBitwiseAnd;
4393 break;
4394 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004395 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004396 binOp = spv::OpLogicalAnd;
4397 break;
4398 case glslang::EOpInclusiveOr:
4399 case glslang::EOpInclusiveOrAssign:
4400 binOp = spv::OpBitwiseOr;
4401 break;
4402 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004403 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004404 binOp = spv::OpLogicalOr;
4405 break;
4406 case glslang::EOpExclusiveOr:
4407 case glslang::EOpExclusiveOrAssign:
4408 binOp = spv::OpBitwiseXor;
4409 break;
4410 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004411 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004412 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004413 break;
4414
4415 case glslang::EOpLessThan:
4416 case glslang::EOpGreaterThan:
4417 case glslang::EOpLessThanEqual:
4418 case glslang::EOpGreaterThanEqual:
4419 case glslang::EOpEqual:
4420 case glslang::EOpNotEqual:
4421 case glslang::EOpVectorEqual:
4422 case glslang::EOpVectorNotEqual:
4423 comparison = true;
4424 break;
4425 default:
4426 break;
4427 }
4428
John Kessenich7c1aa102015-10-15 13:29:11 -06004429 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004430 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004431 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004432 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004433 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004434
4435 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004436 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004437 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004438
qining25262b32016-05-06 17:25:16 -04004439 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004440 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004441 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004442 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004443 }
4444
4445 if (! comparison)
4446 return 0;
4447
John Kessenich7c1aa102015-10-15 13:29:11 -06004448 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004449
John Kessenich4583b612016-08-07 19:14:22 -06004450 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004451 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4452 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004453 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004454 return result;
4455 }
John Kessenich140f3df2015-06-26 16:58:36 -06004456
4457 switch (op) {
4458 case glslang::EOpLessThan:
4459 if (isFloat)
4460 binOp = spv::OpFOrdLessThan;
4461 else if (isUnsigned)
4462 binOp = spv::OpULessThan;
4463 else
4464 binOp = spv::OpSLessThan;
4465 break;
4466 case glslang::EOpGreaterThan:
4467 if (isFloat)
4468 binOp = spv::OpFOrdGreaterThan;
4469 else if (isUnsigned)
4470 binOp = spv::OpUGreaterThan;
4471 else
4472 binOp = spv::OpSGreaterThan;
4473 break;
4474 case glslang::EOpLessThanEqual:
4475 if (isFloat)
4476 binOp = spv::OpFOrdLessThanEqual;
4477 else if (isUnsigned)
4478 binOp = spv::OpULessThanEqual;
4479 else
4480 binOp = spv::OpSLessThanEqual;
4481 break;
4482 case glslang::EOpGreaterThanEqual:
4483 if (isFloat)
4484 binOp = spv::OpFOrdGreaterThanEqual;
4485 else if (isUnsigned)
4486 binOp = spv::OpUGreaterThanEqual;
4487 else
4488 binOp = spv::OpSGreaterThanEqual;
4489 break;
4490 case glslang::EOpEqual:
4491 case glslang::EOpVectorEqual:
4492 if (isFloat)
4493 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004494 else if (isBool)
4495 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004496 else
4497 binOp = spv::OpIEqual;
4498 break;
4499 case glslang::EOpNotEqual:
4500 case glslang::EOpVectorNotEqual:
4501 if (isFloat)
4502 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004503 else if (isBool)
4504 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004505 else
4506 binOp = spv::OpINotEqual;
4507 break;
4508 default:
4509 break;
4510 }
4511
qining25262b32016-05-06 17:25:16 -04004512 if (binOp != spv::OpNop) {
4513 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004514 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004515 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004516 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004517 }
John Kessenich140f3df2015-06-26 16:58:36 -06004518
4519 return 0;
4520}
4521
John Kessenich04bb8a02015-12-12 12:28:14 -07004522//
4523// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4524// These can be any of:
4525//
4526// matrix * scalar
4527// scalar * matrix
4528// matrix * matrix linear algebraic
4529// matrix * vector
4530// vector * matrix
4531// matrix * matrix componentwise
4532// matrix op matrix op in {+, -, /}
4533// matrix op scalar op in {+, -, /}
4534// scalar op matrix op in {+, -, /}
4535//
John Kessenichead86222018-03-28 18:01:20 -06004536spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4537 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004538{
4539 bool firstClass = true;
4540
4541 // First, handle first-class matrix operations (* and matrix/scalar)
4542 switch (op) {
4543 case spv::OpFDiv:
4544 if (builder.isMatrix(left) && builder.isScalar(right)) {
4545 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004546 spv::Id resultType = builder.getTypeId(right);
4547 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004548 op = spv::OpMatrixTimesScalar;
4549 } else
4550 firstClass = false;
4551 break;
4552 case spv::OpMatrixTimesScalar:
4553 if (builder.isMatrix(right))
4554 std::swap(left, right);
4555 assert(builder.isScalar(right));
4556 break;
4557 case spv::OpVectorTimesMatrix:
4558 assert(builder.isVector(left));
4559 assert(builder.isMatrix(right));
4560 break;
4561 case spv::OpMatrixTimesVector:
4562 assert(builder.isMatrix(left));
4563 assert(builder.isVector(right));
4564 break;
4565 case spv::OpMatrixTimesMatrix:
4566 assert(builder.isMatrix(left));
4567 assert(builder.isMatrix(right));
4568 break;
4569 default:
4570 firstClass = false;
4571 break;
4572 }
4573
qining25262b32016-05-06 17:25:16 -04004574 if (firstClass) {
4575 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004576 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004577 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004578 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004579 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004580
LoopDawg592860c2016-06-09 08:57:35 -06004581 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004582 // The result type of all of them is the same type as the (a) matrix operand.
4583 // The algorithm is to:
4584 // - break the matrix(es) into vectors
4585 // - smear any scalar to a vector
4586 // - do vector operations
4587 // - make a matrix out the vector results
4588 switch (op) {
4589 case spv::OpFAdd:
4590 case spv::OpFSub:
4591 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004592 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004593 case spv::OpFMul:
4594 {
4595 // one time set up...
4596 bool leftMat = builder.isMatrix(left);
4597 bool rightMat = builder.isMatrix(right);
4598 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4599 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4600 spv::Id scalarType = builder.getScalarTypeId(typeId);
4601 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4602 std::vector<spv::Id> results;
4603 spv::Id smearVec = spv::NoResult;
4604 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004605 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004606 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004607 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004608
4609 // do each vector op
4610 for (unsigned int c = 0; c < numCols; ++c) {
4611 std::vector<unsigned int> indexes;
4612 indexes.push_back(c);
4613 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4614 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004615 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004616 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004617 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004618 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004619 }
4620
4621 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004622 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004623 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004624 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004625 }
4626 default:
4627 assert(0);
4628 return spv::NoResult;
4629 }
4630}
4631
John Kessenichead86222018-03-28 18:01:20 -06004632spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4633 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004634{
4635 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004636 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004637 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004638 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4639 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004640
4641 switch (op) {
4642 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004643 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004644 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004645 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004646 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004647 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004648 unaryOp = spv::OpSNegate;
4649 break;
4650
4651 case glslang::EOpLogicalNot:
4652 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004653 unaryOp = spv::OpLogicalNot;
4654 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004655 case glslang::EOpBitwiseNot:
4656 unaryOp = spv::OpNot;
4657 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004658
John Kessenich140f3df2015-06-26 16:58:36 -06004659 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004660 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004661 break;
4662 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004663 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665 case glslang::EOpTranspose:
4666 unaryOp = spv::OpTranspose;
4667 break;
4668
4669 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004670 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004671 break;
4672 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004673 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004674 break;
4675 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004676 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004677 break;
4678 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004679 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004680 break;
4681 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004682 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004683 break;
4684 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004685 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004686 break;
4687 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004688 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004689 break;
4690 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004691 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004692 break;
4693
4694 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004695 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004696 break;
4697 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004698 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004699 break;
4700 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004701 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004702 break;
4703 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004704 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004705 break;
4706 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004707 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004708 break;
4709 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004710 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004711 break;
4712
4713 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004714 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004715 break;
4716 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004717 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004718 break;
4719
4720 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004724 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004725 break;
4726 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004727 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004728 break;
4729 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004730 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004731 break;
4732 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004733 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004734 break;
4735 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004736 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004737 break;
4738
4739 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004740 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004741 break;
4742 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004743 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004744 break;
4745 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004746 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004747 break;
4748 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004749 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004750 break;
4751 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004752 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004753 break;
4754 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004755 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004756 break;
4757
4758 case glslang::EOpIsNan:
4759 unaryOp = spv::OpIsNan;
4760 break;
4761 case glslang::EOpIsInf:
4762 unaryOp = spv::OpIsInf;
4763 break;
LoopDawg592860c2016-06-09 08:57:35 -06004764 case glslang::EOpIsFinite:
4765 unaryOp = spv::OpIsFinite;
4766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004767
Rex Xucbc426e2015-12-15 16:03:10 +08004768 case glslang::EOpFloatBitsToInt:
4769 case glslang::EOpFloatBitsToUint:
4770 case glslang::EOpIntBitsToFloat:
4771 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004772 case glslang::EOpDoubleBitsToInt64:
4773 case glslang::EOpDoubleBitsToUint64:
4774 case glslang::EOpInt64BitsToDouble:
4775 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004776 case glslang::EOpFloat16BitsToInt16:
4777 case glslang::EOpFloat16BitsToUint16:
4778 case glslang::EOpInt16BitsToFloat16:
4779 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004780 unaryOp = spv::OpBitcast;
4781 break;
4782
John Kessenich140f3df2015-06-26 16:58:36 -06004783 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004784 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004785 break;
4786 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004787 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004788 break;
4789 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004790 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004791 break;
4792 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004793 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004794 break;
4795 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004796 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004797 break;
4798 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004799 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004800 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004801 case glslang::EOpPackSnorm4x8:
4802 libCall = spv::GLSLstd450PackSnorm4x8;
4803 break;
4804 case glslang::EOpUnpackSnorm4x8:
4805 libCall = spv::GLSLstd450UnpackSnorm4x8;
4806 break;
4807 case glslang::EOpPackUnorm4x8:
4808 libCall = spv::GLSLstd450PackUnorm4x8;
4809 break;
4810 case glslang::EOpUnpackUnorm4x8:
4811 libCall = spv::GLSLstd450UnpackUnorm4x8;
4812 break;
4813 case glslang::EOpPackDouble2x32:
4814 libCall = spv::GLSLstd450PackDouble2x32;
4815 break;
4816 case glslang::EOpUnpackDouble2x32:
4817 libCall = spv::GLSLstd450UnpackDouble2x32;
4818 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004819
Rex Xu8ff43de2016-04-22 16:51:45 +08004820 case glslang::EOpPackInt2x32:
4821 case glslang::EOpUnpackInt2x32:
4822 case glslang::EOpPackUint2x32:
4823 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004824 case glslang::EOpPack16:
4825 case glslang::EOpPack32:
4826 case glslang::EOpPack64:
4827 case glslang::EOpUnpack32:
4828 case glslang::EOpUnpack16:
4829 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004830 case glslang::EOpPackInt2x16:
4831 case glslang::EOpUnpackInt2x16:
4832 case glslang::EOpPackUint2x16:
4833 case glslang::EOpUnpackUint2x16:
4834 case glslang::EOpPackInt4x16:
4835 case glslang::EOpUnpackInt4x16:
4836 case glslang::EOpPackUint4x16:
4837 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004838 case glslang::EOpPackFloat2x16:
4839 case glslang::EOpUnpackFloat2x16:
4840 unaryOp = spv::OpBitcast;
4841 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004842
John Kessenich140f3df2015-06-26 16:58:36 -06004843 case glslang::EOpDPdx:
4844 unaryOp = spv::OpDPdx;
4845 break;
4846 case glslang::EOpDPdy:
4847 unaryOp = spv::OpDPdy;
4848 break;
4849 case glslang::EOpFwidth:
4850 unaryOp = spv::OpFwidth;
4851 break;
4852 case glslang::EOpDPdxFine:
4853 unaryOp = spv::OpDPdxFine;
4854 break;
4855 case glslang::EOpDPdyFine:
4856 unaryOp = spv::OpDPdyFine;
4857 break;
4858 case glslang::EOpFwidthFine:
4859 unaryOp = spv::OpFwidthFine;
4860 break;
4861 case glslang::EOpDPdxCoarse:
4862 unaryOp = spv::OpDPdxCoarse;
4863 break;
4864 case glslang::EOpDPdyCoarse:
4865 unaryOp = spv::OpDPdyCoarse;
4866 break;
4867 case glslang::EOpFwidthCoarse:
4868 unaryOp = spv::OpFwidthCoarse;
4869 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004870 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004871#ifdef AMD_EXTENSIONS
4872 if (typeProxy == glslang::EbtFloat16)
4873 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4874#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004875 libCall = spv::GLSLstd450InterpolateAtCentroid;
4876 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004877 case glslang::EOpAny:
4878 unaryOp = spv::OpAny;
4879 break;
4880 case glslang::EOpAll:
4881 unaryOp = spv::OpAll;
4882 break;
4883
4884 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004885 if (isFloat)
4886 libCall = spv::GLSLstd450FAbs;
4887 else
4888 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004889 break;
4890 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004891 if (isFloat)
4892 libCall = spv::GLSLstd450FSign;
4893 else
4894 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004895 break;
4896
John Kessenichfc51d282015-08-19 13:34:18 -06004897 case glslang::EOpAtomicCounterIncrement:
4898 case glslang::EOpAtomicCounterDecrement:
4899 case glslang::EOpAtomicCounter:
4900 {
4901 // Handle all of the atomics in one place, in createAtomicOperation()
4902 std::vector<spv::Id> operands;
4903 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004904 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004905 }
4906
John Kessenichfc51d282015-08-19 13:34:18 -06004907 case glslang::EOpBitFieldReverse:
4908 unaryOp = spv::OpBitReverse;
4909 break;
4910 case glslang::EOpBitCount:
4911 unaryOp = spv::OpBitCount;
4912 break;
4913 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004914 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004915 break;
4916 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004917 if (isUnsigned)
4918 libCall = spv::GLSLstd450FindUMsb;
4919 else
4920 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004921 break;
4922
Rex Xu574ab042016-04-14 16:53:07 +08004923 case glslang::EOpBallot:
4924 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004925 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004926 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004927 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004928#ifdef AMD_EXTENSIONS
4929 case glslang::EOpMinInvocations:
4930 case glslang::EOpMaxInvocations:
4931 case glslang::EOpAddInvocations:
4932 case glslang::EOpMinInvocationsNonUniform:
4933 case glslang::EOpMaxInvocationsNonUniform:
4934 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004935 case glslang::EOpMinInvocationsInclusiveScan:
4936 case glslang::EOpMaxInvocationsInclusiveScan:
4937 case glslang::EOpAddInvocationsInclusiveScan:
4938 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4939 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4940 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4941 case glslang::EOpMinInvocationsExclusiveScan:
4942 case glslang::EOpMaxInvocationsExclusiveScan:
4943 case glslang::EOpAddInvocationsExclusiveScan:
4944 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4945 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4946 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004947#endif
Rex Xu51596642016-09-21 18:56:12 +08004948 {
4949 std::vector<spv::Id> operands;
4950 operands.push_back(operand);
4951 return createInvocationsOperation(op, typeId, operands, typeProxy);
4952 }
John Kessenich66011cb2018-03-06 16:12:04 -07004953 case glslang::EOpSubgroupAll:
4954 case glslang::EOpSubgroupAny:
4955 case glslang::EOpSubgroupAllEqual:
4956 case glslang::EOpSubgroupBroadcastFirst:
4957 case glslang::EOpSubgroupBallot:
4958 case glslang::EOpSubgroupInverseBallot:
4959 case glslang::EOpSubgroupBallotBitCount:
4960 case glslang::EOpSubgroupBallotInclusiveBitCount:
4961 case glslang::EOpSubgroupBallotExclusiveBitCount:
4962 case glslang::EOpSubgroupBallotFindLSB:
4963 case glslang::EOpSubgroupBallotFindMSB:
4964 case glslang::EOpSubgroupAdd:
4965 case glslang::EOpSubgroupMul:
4966 case glslang::EOpSubgroupMin:
4967 case glslang::EOpSubgroupMax:
4968 case glslang::EOpSubgroupAnd:
4969 case glslang::EOpSubgroupOr:
4970 case glslang::EOpSubgroupXor:
4971 case glslang::EOpSubgroupInclusiveAdd:
4972 case glslang::EOpSubgroupInclusiveMul:
4973 case glslang::EOpSubgroupInclusiveMin:
4974 case glslang::EOpSubgroupInclusiveMax:
4975 case glslang::EOpSubgroupInclusiveAnd:
4976 case glslang::EOpSubgroupInclusiveOr:
4977 case glslang::EOpSubgroupInclusiveXor:
4978 case glslang::EOpSubgroupExclusiveAdd:
4979 case glslang::EOpSubgroupExclusiveMul:
4980 case glslang::EOpSubgroupExclusiveMin:
4981 case glslang::EOpSubgroupExclusiveMax:
4982 case glslang::EOpSubgroupExclusiveAnd:
4983 case glslang::EOpSubgroupExclusiveOr:
4984 case glslang::EOpSubgroupExclusiveXor:
4985 case glslang::EOpSubgroupQuadSwapHorizontal:
4986 case glslang::EOpSubgroupQuadSwapVertical:
4987 case glslang::EOpSubgroupQuadSwapDiagonal: {
4988 std::vector<spv::Id> operands;
4989 operands.push_back(operand);
4990 return createSubgroupOperation(op, typeId, operands, typeProxy);
4991 }
Rex Xu9d93a232016-05-05 12:30:44 +08004992#ifdef AMD_EXTENSIONS
4993 case glslang::EOpMbcnt:
4994 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4995 libCall = spv::MbcntAMD;
4996 break;
4997
4998 case glslang::EOpCubeFaceIndex:
4999 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5000 libCall = spv::CubeFaceIndexAMD;
5001 break;
5002
5003 case glslang::EOpCubeFaceCoord:
5004 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5005 libCall = spv::CubeFaceCoordAMD;
5006 break;
5007#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005008#ifdef NV_EXTENSIONS
5009 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005010 unaryOp = spv::OpGroupNonUniformPartitionNV;
5011 break;
5012#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005013 default:
5014 return 0;
5015 }
5016
5017 spv::Id id;
5018 if (libCall >= 0) {
5019 std::vector<spv::Id> args;
5020 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005021 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005022 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005023 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005024 }
John Kessenich140f3df2015-06-26 16:58:36 -06005025
John Kessenichead86222018-03-28 18:01:20 -06005026 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005027 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005028 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005029}
5030
John Kessenich7a53f762016-01-20 11:19:27 -07005031// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005032spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5033 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005034{
5035 // Handle unary operations vector by vector.
5036 // The result type is the same type as the original type.
5037 // The algorithm is to:
5038 // - break the matrix into vectors
5039 // - apply the operation to each vector
5040 // - make a matrix out the vector results
5041
5042 // get the types sorted out
5043 int numCols = builder.getNumColumns(operand);
5044 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005045 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5046 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005047 std::vector<spv::Id> results;
5048
5049 // do each vector op
5050 for (int c = 0; c < numCols; ++c) {
5051 std::vector<unsigned int> indexes;
5052 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005053 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5054 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005055 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005056 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005057 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005058 }
5059
5060 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005061 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005062 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005063 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005064}
5065
John Kessenichad7645f2018-06-04 19:11:25 -06005066// For converting integers where both the bitwidth and the signedness could
5067// change, but only do the width change here. The caller is still responsible
5068// for the signedness conversion.
5069spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005070{
John Kessenichad7645f2018-06-04 19:11:25 -06005071 // Get the result type width, based on the type to convert to.
5072 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005073 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005074 case glslang::EOpConvInt16ToUint8:
5075 case glslang::EOpConvIntToUint8:
5076 case glslang::EOpConvInt64ToUint8:
5077 case glslang::EOpConvUint16ToInt8:
5078 case glslang::EOpConvUintToInt8:
5079 case glslang::EOpConvUint64ToInt8:
5080 width = 8;
5081 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005082 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005083 case glslang::EOpConvIntToUint16:
5084 case glslang::EOpConvInt64ToUint16:
5085 case glslang::EOpConvUint8ToInt16:
5086 case glslang::EOpConvUintToInt16:
5087 case glslang::EOpConvUint64ToInt16:
5088 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005089 break;
5090 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005091 case glslang::EOpConvInt16ToUint:
5092 case glslang::EOpConvInt64ToUint:
5093 case glslang::EOpConvUint8ToInt:
5094 case glslang::EOpConvUint16ToInt:
5095 case glslang::EOpConvUint64ToInt:
5096 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005097 break;
5098 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005099 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005100 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005101 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005102 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005103 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005104 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005105 break;
5106
5107 default:
5108 assert(false && "Default missing");
5109 break;
5110 }
5111
John Kessenichad7645f2018-06-04 19:11:25 -06005112 // Get the conversion operation and result type,
5113 // based on the target width, but the source type.
5114 spv::Id type = spv::NoType;
5115 spv::Op convOp = spv::OpNop;
5116 switch(op) {
5117 case glslang::EOpConvInt8ToUint16:
5118 case glslang::EOpConvInt8ToUint:
5119 case glslang::EOpConvInt8ToUint64:
5120 case glslang::EOpConvInt16ToUint8:
5121 case glslang::EOpConvInt16ToUint:
5122 case glslang::EOpConvInt16ToUint64:
5123 case glslang::EOpConvIntToUint8:
5124 case glslang::EOpConvIntToUint16:
5125 case glslang::EOpConvIntToUint64:
5126 case glslang::EOpConvInt64ToUint8:
5127 case glslang::EOpConvInt64ToUint16:
5128 case glslang::EOpConvInt64ToUint:
5129 convOp = spv::OpSConvert;
5130 type = builder.makeIntType(width);
5131 break;
5132 default:
5133 convOp = spv::OpUConvert;
5134 type = builder.makeUintType(width);
5135 break;
5136 }
5137
John Kessenich66011cb2018-03-06 16:12:04 -07005138 if (vectorSize > 0)
5139 type = builder.makeVectorType(type, vectorSize);
5140
John Kessenichad7645f2018-06-04 19:11:25 -06005141 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005142}
5143
John Kessenichead86222018-03-28 18:01:20 -06005144spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5145 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005146{
5147 spv::Op convOp = spv::OpNop;
5148 spv::Id zero = 0;
5149 spv::Id one = 0;
5150
5151 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5152
5153 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005154 case glslang::EOpConvInt8ToBool:
5155 case glslang::EOpConvUint8ToBool:
5156 zero = builder.makeUint8Constant(0);
5157 zero = makeSmearedConstant(zero, vectorSize);
5158 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005159 case glslang::EOpConvInt16ToBool:
5160 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005161 zero = builder.makeUint16Constant(0);
5162 zero = makeSmearedConstant(zero, vectorSize);
5163 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5164 case glslang::EOpConvIntToBool:
5165 case glslang::EOpConvUintToBool:
5166 zero = builder.makeUintConstant(0);
5167 zero = makeSmearedConstant(zero, vectorSize);
5168 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5169 case glslang::EOpConvInt64ToBool:
5170 case glslang::EOpConvUint64ToBool:
5171 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005172 zero = makeSmearedConstant(zero, vectorSize);
5173 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5174
5175 case glslang::EOpConvFloatToBool:
5176 zero = builder.makeFloatConstant(0.0F);
5177 zero = makeSmearedConstant(zero, vectorSize);
5178 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5179
5180 case glslang::EOpConvDoubleToBool:
5181 zero = builder.makeDoubleConstant(0.0);
5182 zero = makeSmearedConstant(zero, vectorSize);
5183 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5184
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005185 case glslang::EOpConvFloat16ToBool:
5186 zero = builder.makeFloat16Constant(0.0F);
5187 zero = makeSmearedConstant(zero, vectorSize);
5188 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005189
John Kessenich140f3df2015-06-26 16:58:36 -06005190 case glslang::EOpConvBoolToFloat:
5191 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005192 zero = builder.makeFloatConstant(0.0F);
5193 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005195
John Kessenich140f3df2015-06-26 16:58:36 -06005196 case glslang::EOpConvBoolToDouble:
5197 convOp = spv::OpSelect;
5198 zero = builder.makeDoubleConstant(0.0);
5199 one = builder.makeDoubleConstant(1.0);
5200 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005201
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005202 case glslang::EOpConvBoolToFloat16:
5203 convOp = spv::OpSelect;
5204 zero = builder.makeFloat16Constant(0.0F);
5205 one = builder.makeFloat16Constant(1.0F);
5206 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005207
5208 case glslang::EOpConvBoolToInt8:
5209 zero = builder.makeInt8Constant(0);
5210 one = builder.makeInt8Constant(1);
5211 convOp = spv::OpSelect;
5212 break;
5213
5214 case glslang::EOpConvBoolToUint8:
5215 zero = builder.makeUint8Constant(0);
5216 one = builder.makeUint8Constant(1);
5217 convOp = spv::OpSelect;
5218 break;
5219
5220 case glslang::EOpConvBoolToInt16:
5221 zero = builder.makeInt16Constant(0);
5222 one = builder.makeInt16Constant(1);
5223 convOp = spv::OpSelect;
5224 break;
5225
5226 case glslang::EOpConvBoolToUint16:
5227 zero = builder.makeUint16Constant(0);
5228 one = builder.makeUint16Constant(1);
5229 convOp = spv::OpSelect;
5230 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005231
John Kessenich140f3df2015-06-26 16:58:36 -06005232 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005233 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005234 if (op == glslang::EOpConvBoolToInt64)
5235 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005236 else
5237 zero = builder.makeIntConstant(0);
5238
5239 if (op == glslang::EOpConvBoolToInt64)
5240 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005241 else
5242 one = builder.makeIntConstant(1);
5243
John Kessenich140f3df2015-06-26 16:58:36 -06005244 convOp = spv::OpSelect;
5245 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005246
John Kessenich140f3df2015-06-26 16:58:36 -06005247 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005248 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005249 if (op == glslang::EOpConvBoolToUint64)
5250 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005251 else
5252 zero = builder.makeUintConstant(0);
5253
5254 if (op == glslang::EOpConvBoolToUint64)
5255 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005256 else
5257 one = builder.makeUintConstant(1);
5258
John Kessenich140f3df2015-06-26 16:58:36 -06005259 convOp = spv::OpSelect;
5260 break;
5261
John Kessenich66011cb2018-03-06 16:12:04 -07005262 case glslang::EOpConvInt8ToFloat16:
5263 case glslang::EOpConvInt8ToFloat:
5264 case glslang::EOpConvInt8ToDouble:
5265 case glslang::EOpConvInt16ToFloat16:
5266 case glslang::EOpConvInt16ToFloat:
5267 case glslang::EOpConvInt16ToDouble:
5268 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005269 case glslang::EOpConvIntToFloat:
5270 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005271 case glslang::EOpConvInt64ToFloat:
5272 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005273 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005274 convOp = spv::OpConvertSToF;
5275 break;
5276
John Kessenich66011cb2018-03-06 16:12:04 -07005277 case glslang::EOpConvUint8ToFloat16:
5278 case glslang::EOpConvUint8ToFloat:
5279 case glslang::EOpConvUint8ToDouble:
5280 case glslang::EOpConvUint16ToFloat16:
5281 case glslang::EOpConvUint16ToFloat:
5282 case glslang::EOpConvUint16ToDouble:
5283 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005284 case glslang::EOpConvUintToFloat:
5285 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005286 case glslang::EOpConvUint64ToFloat:
5287 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005288 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005289 convOp = spv::OpConvertUToF;
5290 break;
5291
5292 case glslang::EOpConvDoubleToFloat:
5293 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005294 case glslang::EOpConvDoubleToFloat16:
5295 case glslang::EOpConvFloat16ToDouble:
5296 case glslang::EOpConvFloatToFloat16:
5297 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005298 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005299 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005300 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005301 break;
5302
John Kessenich66011cb2018-03-06 16:12:04 -07005303 case glslang::EOpConvFloat16ToInt8:
5304 case glslang::EOpConvFloatToInt8:
5305 case glslang::EOpConvDoubleToInt8:
5306 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005307 case glslang::EOpConvFloatToInt16:
5308 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005309 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005310 case glslang::EOpConvFloatToInt:
5311 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005312 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005313 case glslang::EOpConvFloatToInt64:
5314 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005315 convOp = spv::OpConvertFToS;
5316 break;
5317
John Kessenich66011cb2018-03-06 16:12:04 -07005318 case glslang::EOpConvUint8ToInt8:
5319 case glslang::EOpConvInt8ToUint8:
5320 case glslang::EOpConvUint16ToInt16:
5321 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005322 case glslang::EOpConvUintToInt:
5323 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005324 case glslang::EOpConvUint64ToInt64:
5325 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005326 if (builder.isInSpecConstCodeGenMode()) {
5327 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005328 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5329 zero = builder.makeUint8Constant(0);
5330 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005331 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005332 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5333 zero = builder.makeUint64Constant(0);
5334 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005335 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005336 }
qining189b2032016-04-12 23:16:20 -04005337 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005338 // Use OpIAdd, instead of OpBitcast to do the conversion when
5339 // generating for OpSpecConstantOp instruction.
5340 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5341 }
5342 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005343 convOp = spv::OpBitcast;
5344 break;
5345
John Kessenich66011cb2018-03-06 16:12:04 -07005346 case glslang::EOpConvFloat16ToUint8:
5347 case glslang::EOpConvFloatToUint8:
5348 case glslang::EOpConvDoubleToUint8:
5349 case glslang::EOpConvFloat16ToUint16:
5350 case glslang::EOpConvFloatToUint16:
5351 case glslang::EOpConvDoubleToUint16:
5352 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005353 case glslang::EOpConvFloatToUint:
5354 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005355 case glslang::EOpConvFloatToUint64:
5356 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005357 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005358 convOp = spv::OpConvertFToU;
5359 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005360
John Kessenich66011cb2018-03-06 16:12:04 -07005361 case glslang::EOpConvInt8ToInt16:
5362 case glslang::EOpConvInt8ToInt:
5363 case glslang::EOpConvInt8ToInt64:
5364 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005365 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005366 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005367 case glslang::EOpConvIntToInt8:
5368 case glslang::EOpConvIntToInt16:
5369 case glslang::EOpConvIntToInt64:
5370 case glslang::EOpConvInt64ToInt8:
5371 case glslang::EOpConvInt64ToInt16:
5372 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005373 convOp = spv::OpSConvert;
5374 break;
5375
John Kessenich66011cb2018-03-06 16:12:04 -07005376 case glslang::EOpConvUint8ToUint16:
5377 case glslang::EOpConvUint8ToUint:
5378 case glslang::EOpConvUint8ToUint64:
5379 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005380 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005381 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005382 case glslang::EOpConvUintToUint8:
5383 case glslang::EOpConvUintToUint16:
5384 case glslang::EOpConvUintToUint64:
5385 case glslang::EOpConvUint64ToUint8:
5386 case glslang::EOpConvUint64ToUint16:
5387 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005388 convOp = spv::OpUConvert;
5389 break;
5390
John Kessenich66011cb2018-03-06 16:12:04 -07005391 case glslang::EOpConvInt8ToUint16:
5392 case glslang::EOpConvInt8ToUint:
5393 case glslang::EOpConvInt8ToUint64:
5394 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005395 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005396 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005397 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005398 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005399 case glslang::EOpConvIntToUint64:
5400 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005401 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005402 case glslang::EOpConvInt64ToUint:
5403 case glslang::EOpConvUint8ToInt16:
5404 case glslang::EOpConvUint8ToInt:
5405 case glslang::EOpConvUint8ToInt64:
5406 case glslang::EOpConvUint16ToInt8:
5407 case glslang::EOpConvUint16ToInt:
5408 case glslang::EOpConvUint16ToInt64:
5409 case glslang::EOpConvUintToInt8:
5410 case glslang::EOpConvUintToInt16:
5411 case glslang::EOpConvUintToInt64:
5412 case glslang::EOpConvUint64ToInt8:
5413 case glslang::EOpConvUint64ToInt16:
5414 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005415 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005416 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005417
5418 if (builder.isInSpecConstCodeGenMode()) {
5419 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005420 switch(op) {
5421 case glslang::EOpConvInt16ToUint8:
5422 case glslang::EOpConvIntToUint8:
5423 case glslang::EOpConvInt64ToUint8:
5424 case glslang::EOpConvUint16ToInt8:
5425 case glslang::EOpConvUintToInt8:
5426 case glslang::EOpConvUint64ToInt8:
5427 zero = builder.makeUint8Constant(0);
5428 break;
5429 case glslang::EOpConvInt8ToUint16:
5430 case glslang::EOpConvIntToUint16:
5431 case glslang::EOpConvInt64ToUint16:
5432 case glslang::EOpConvUint8ToInt16:
5433 case glslang::EOpConvUintToInt16:
5434 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005435 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005436 break;
5437 case glslang::EOpConvInt8ToUint:
5438 case glslang::EOpConvInt16ToUint:
5439 case glslang::EOpConvInt64ToUint:
5440 case glslang::EOpConvUint8ToInt:
5441 case glslang::EOpConvUint16ToInt:
5442 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005443 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005444 break;
5445 case glslang::EOpConvInt8ToUint64:
5446 case glslang::EOpConvInt16ToUint64:
5447 case glslang::EOpConvIntToUint64:
5448 case glslang::EOpConvUint8ToInt64:
5449 case glslang::EOpConvUint16ToInt64:
5450 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005451 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005452 break;
5453 default:
5454 assert(false && "Default missing");
5455 break;
5456 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005457 zero = makeSmearedConstant(zero, vectorSize);
5458 // Use OpIAdd, instead of OpBitcast to do the conversion when
5459 // generating for OpSpecConstantOp instruction.
5460 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5461 }
5462 // For normal run-time conversion instruction, use OpBitcast.
5463 convOp = spv::OpBitcast;
5464 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 default:
5466 break;
5467 }
5468
5469 spv::Id result = 0;
5470 if (convOp == spv::OpNop)
5471 return result;
5472
5473 if (convOp == spv::OpSelect) {
5474 zero = makeSmearedConstant(zero, vectorSize);
5475 one = makeSmearedConstant(one, vectorSize);
5476 result = builder.createTriOp(convOp, destType, operand, one, zero);
5477 } else
5478 result = builder.createUnaryOp(convOp, destType, operand);
5479
John Kessenichead86222018-03-28 18:01:20 -06005480 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005481 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005482 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005483}
5484
5485spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5486{
5487 if (vectorSize == 0)
5488 return constant;
5489
5490 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5491 std::vector<spv::Id> components;
5492 for (int c = 0; c < vectorSize; ++c)
5493 components.push_back(constant);
5494 return builder.makeCompositeConstant(vectorTypeId, components);
5495}
5496
John Kessenich426394d2015-07-23 10:22:48 -06005497// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005498spv::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 -06005499{
5500 spv::Op opCode = spv::OpNop;
5501
5502 switch (op) {
5503 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005504 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005505 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005506 opCode = spv::OpAtomicIAdd;
5507 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005508 case glslang::EOpAtomicCounterSubtract:
5509 opCode = spv::OpAtomicISub;
5510 break;
John Kessenich426394d2015-07-23 10:22:48 -06005511 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005512 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005513 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005514 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005515 break;
5516 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005517 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005518 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005519 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005520 break;
5521 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005522 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005523 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005524 opCode = spv::OpAtomicAnd;
5525 break;
5526 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005527 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005528 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005529 opCode = spv::OpAtomicOr;
5530 break;
5531 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005532 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005533 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005534 opCode = spv::OpAtomicXor;
5535 break;
5536 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005537 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005538 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005539 opCode = spv::OpAtomicExchange;
5540 break;
5541 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005542 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005543 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005544 opCode = spv::OpAtomicCompareExchange;
5545 break;
5546 case glslang::EOpAtomicCounterIncrement:
5547 opCode = spv::OpAtomicIIncrement;
5548 break;
5549 case glslang::EOpAtomicCounterDecrement:
5550 opCode = spv::OpAtomicIDecrement;
5551 break;
5552 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005553 case glslang::EOpImageAtomicLoad:
5554 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005555 opCode = spv::OpAtomicLoad;
5556 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005557 case glslang::EOpAtomicStore:
5558 case glslang::EOpImageAtomicStore:
5559 opCode = spv::OpAtomicStore;
5560 break;
John Kessenich426394d2015-07-23 10:22:48 -06005561 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005562 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005563 break;
5564 }
5565
Rex Xue8fe8b02017-09-26 15:42:56 +08005566 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5567 builder.addCapability(spv::CapabilityInt64Atomics);
5568
John Kessenich426394d2015-07-23 10:22:48 -06005569 // Sort out the operands
5570 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005571 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005572 // - compare-exchange swaps the value and comparator
5573 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005574 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005575 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5576 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5577 spv::Id scopeId;
5578 if (glslangIntermediate->usingVulkanMemoryModel()) {
5579 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5580 } else {
5581 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5582 }
5583 // semantics default to relaxed
5584 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5585 spv::Id semanticsId2 = semanticsId;
5586
5587 pointerId = operands[0];
5588 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5589 // no additional operands
5590 } else if (opCode == spv::OpAtomicCompareExchange) {
5591 compareId = operands[1];
5592 valueId = operands[2];
5593 if (operands.size() > 3) {
5594 scopeId = operands[3];
5595 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5596 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5597 }
5598 } else if (opCode == spv::OpAtomicLoad) {
5599 if (operands.size() > 1) {
5600 scopeId = operands[1];
5601 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5602 }
5603 } else {
5604 // atomic store or RMW
5605 valueId = operands[1];
5606 if (operands.size() > 2) {
5607 scopeId = operands[2];
5608 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5609 }
Rex Xu04db3f52015-09-16 11:44:02 +08005610 }
John Kessenich426394d2015-07-23 10:22:48 -06005611
Jeff Bolz36831c92018-09-05 10:11:41 -05005612 // Check for capabilities
5613 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5614 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5615 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5616 }
John Kessenich426394d2015-07-23 10:22:48 -06005617
Jeff Bolz36831c92018-09-05 10:11:41 -05005618 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5619 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5620 }
John Kessenich48d6e792017-10-06 21:21:48 -06005621
Jeff Bolz36831c92018-09-05 10:11:41 -05005622 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5623 spvAtomicOperands.push_back(pointerId);
5624 spvAtomicOperands.push_back(scopeId);
5625 spvAtomicOperands.push_back(semanticsId);
5626 if (opCode == spv::OpAtomicCompareExchange) {
5627 spvAtomicOperands.push_back(semanticsId2);
5628 spvAtomicOperands.push_back(valueId);
5629 spvAtomicOperands.push_back(compareId);
5630 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5631 spvAtomicOperands.push_back(valueId);
5632 }
John Kessenich48d6e792017-10-06 21:21:48 -06005633
Jeff Bolz36831c92018-09-05 10:11:41 -05005634 if (opCode == spv::OpAtomicStore) {
5635 builder.createNoResultOp(opCode, spvAtomicOperands);
5636 return 0;
5637 } else {
5638 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5639
5640 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5641 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5642 if (op == glslang::EOpAtomicCounterDecrement)
5643 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5644
5645 return resultId;
5646 }
John Kessenich426394d2015-07-23 10:22:48 -06005647}
5648
John Kessenich91cef522016-05-05 16:45:40 -06005649// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005650spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005651{
Corentin Walleze7061422018-08-08 15:20:15 +02005652#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005653 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5654 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005655#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005656
Rex Xu51596642016-09-21 18:56:12 +08005657 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005658 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005659 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5660
chaocf200da82016-12-20 12:44:35 -08005661 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5662 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005663 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5664 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005665 } else if (op == glslang::EOpAnyInvocation ||
5666 op == glslang::EOpAllInvocations ||
5667 op == glslang::EOpAllInvocationsEqual) {
5668 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5669 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005670 } else {
5671 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005672#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005673 if (op == glslang::EOpMinInvocationsNonUniform ||
5674 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005675 op == glslang::EOpAddInvocationsNonUniform ||
5676 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5677 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5678 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5679 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5680 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5681 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005682 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005683#endif
Rex Xu51596642016-09-21 18:56:12 +08005684
Rex Xu9d93a232016-05-05 12:30:44 +08005685#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005686 switch (op) {
5687 case glslang::EOpMinInvocations:
5688 case glslang::EOpMaxInvocations:
5689 case glslang::EOpAddInvocations:
5690 case glslang::EOpMinInvocationsNonUniform:
5691 case glslang::EOpMaxInvocationsNonUniform:
5692 case glslang::EOpAddInvocationsNonUniform:
5693 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005694 break;
5695 case glslang::EOpMinInvocationsInclusiveScan:
5696 case glslang::EOpMaxInvocationsInclusiveScan:
5697 case glslang::EOpAddInvocationsInclusiveScan:
5698 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5699 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5700 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5701 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005702 break;
5703 case glslang::EOpMinInvocationsExclusiveScan:
5704 case glslang::EOpMaxInvocationsExclusiveScan:
5705 case glslang::EOpAddInvocationsExclusiveScan:
5706 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5707 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5708 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5709 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005710 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005711 default:
5712 break;
Rex Xu430ef402016-10-14 17:22:23 +08005713 }
John Kessenich149afc32018-08-14 13:31:43 -06005714 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5715 spvGroupOperands.push_back(scope);
5716 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005717 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005718 spvGroupOperands.push_back(groupOp);
5719 }
Rex Xu9d93a232016-05-05 12:30:44 +08005720#endif
Rex Xu51596642016-09-21 18:56:12 +08005721 }
5722
John Kessenich149afc32018-08-14 13:31:43 -06005723 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5724 spv::IdImmediate op = { true, *opIt };
5725 spvGroupOperands.push_back(op);
5726 }
John Kessenich91cef522016-05-05 16:45:40 -06005727
5728 switch (op) {
5729 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005730 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005731 break;
John Kessenich91cef522016-05-05 16:45:40 -06005732 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005733 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005734 break;
John Kessenich91cef522016-05-05 16:45:40 -06005735 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005736 opCode = spv::OpSubgroupAllEqualKHR;
5737 break;
Rex Xu51596642016-09-21 18:56:12 +08005738 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005739 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005740 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005741 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005742 break;
5743 case glslang::EOpReadFirstInvocation:
5744 opCode = spv::OpSubgroupFirstInvocationKHR;
5745 break;
5746 case glslang::EOpBallot:
5747 {
5748 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5749 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5750 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5751 //
5752 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5753 //
5754 spv::Id uintType = builder.makeUintType(32);
5755 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5756 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5757
5758 std::vector<spv::Id> components;
5759 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5760 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5761
5762 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5763 return builder.createUnaryOp(spv::OpBitcast, typeId,
5764 builder.createCompositeConstruct(uvec2Type, components));
5765 }
5766
Rex Xu9d93a232016-05-05 12:30:44 +08005767#ifdef AMD_EXTENSIONS
5768 case glslang::EOpMinInvocations:
5769 case glslang::EOpMaxInvocations:
5770 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005771 case glslang::EOpMinInvocationsInclusiveScan:
5772 case glslang::EOpMaxInvocationsInclusiveScan:
5773 case glslang::EOpAddInvocationsInclusiveScan:
5774 case glslang::EOpMinInvocationsExclusiveScan:
5775 case glslang::EOpMaxInvocationsExclusiveScan:
5776 case glslang::EOpAddInvocationsExclusiveScan:
5777 if (op == glslang::EOpMinInvocations ||
5778 op == glslang::EOpMinInvocationsInclusiveScan ||
5779 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005780 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005781 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005782 else {
5783 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005784 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005785 else
Rex Xu51596642016-09-21 18:56:12 +08005786 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005787 }
Rex Xu430ef402016-10-14 17:22:23 +08005788 } else if (op == glslang::EOpMaxInvocations ||
5789 op == glslang::EOpMaxInvocationsInclusiveScan ||
5790 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005791 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005792 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005793 else {
5794 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005795 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005796 else
Rex Xu51596642016-09-21 18:56:12 +08005797 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005798 }
5799 } else {
5800 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005801 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005802 else
Rex Xu51596642016-09-21 18:56:12 +08005803 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005804 }
5805
Rex Xu2bbbe062016-08-23 15:41:05 +08005806 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005807 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005808
5809 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005810 case glslang::EOpMinInvocationsNonUniform:
5811 case glslang::EOpMaxInvocationsNonUniform:
5812 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005813 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5814 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5815 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5816 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5817 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5818 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5819 if (op == glslang::EOpMinInvocationsNonUniform ||
5820 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5821 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005822 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005823 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005824 else {
5825 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005826 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005827 else
Rex Xu51596642016-09-21 18:56:12 +08005828 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005829 }
5830 }
Rex Xu430ef402016-10-14 17:22:23 +08005831 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5832 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5833 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005834 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005835 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005836 else {
5837 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005838 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005839 else
Rex Xu51596642016-09-21 18:56:12 +08005840 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005841 }
5842 }
5843 else {
5844 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005845 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005846 else
Rex Xu51596642016-09-21 18:56:12 +08005847 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005848 }
5849
Rex Xu2bbbe062016-08-23 15:41:05 +08005850 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005851 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005852
5853 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005854#endif
John Kessenich91cef522016-05-05 16:45:40 -06005855 default:
5856 logger->missingFunctionality("invocation operation");
5857 return spv::NoResult;
5858 }
Rex Xu51596642016-09-21 18:56:12 +08005859
5860 assert(opCode != spv::OpNop);
5861 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005862}
5863
Rex Xu2bbbe062016-08-23 15:41:05 +08005864// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005865spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5866 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005867{
Rex Xub7072052016-09-26 15:53:40 +08005868#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005869 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5870 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005871 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005872 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005873 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5874 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5875 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005876#else
5877 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5878 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005879 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5880 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005881#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005882
5883 // Handle group invocation operations scalar by scalar.
5884 // The result type is the same type as the original type.
5885 // The algorithm is to:
5886 // - break the vector into scalars
5887 // - apply the operation to each scalar
5888 // - make a vector out the scalar results
5889
5890 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005891 int numComponents = builder.getNumComponents(operands[0]);
5892 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005893 std::vector<spv::Id> results;
5894
5895 // do each scalar op
5896 for (int comp = 0; comp < numComponents; ++comp) {
5897 std::vector<unsigned int> indexes;
5898 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005899 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5900 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005901 if (op == spv::OpSubgroupReadInvocationKHR) {
5902 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005903 spv::IdImmediate operand = { true, operands[1] };
5904 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005905 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005906 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5907 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005908 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005909 spv::IdImmediate operand = { true, operands[1] };
5910 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005911 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005912 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5913 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06005914 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005915 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005916 spvGroupOperands.push_back(scalar);
5917 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005918
Rex Xub7072052016-09-26 15:53:40 +08005919 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005920 }
5921
5922 // put the pieces together
5923 return builder.createCompositeConstruct(typeId, results);
5924}
Rex Xu2bbbe062016-08-23 15:41:05 +08005925
John Kessenich66011cb2018-03-06 16:12:04 -07005926// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005927spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5928 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005929{
5930 // Add the required capabilities.
5931 switch (op) {
5932 case glslang::EOpSubgroupElect:
5933 builder.addCapability(spv::CapabilityGroupNonUniform);
5934 break;
5935 case glslang::EOpSubgroupAll:
5936 case glslang::EOpSubgroupAny:
5937 case glslang::EOpSubgroupAllEqual:
5938 builder.addCapability(spv::CapabilityGroupNonUniform);
5939 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5940 break;
5941 case glslang::EOpSubgroupBroadcast:
5942 case glslang::EOpSubgroupBroadcastFirst:
5943 case glslang::EOpSubgroupBallot:
5944 case glslang::EOpSubgroupInverseBallot:
5945 case glslang::EOpSubgroupBallotBitExtract:
5946 case glslang::EOpSubgroupBallotBitCount:
5947 case glslang::EOpSubgroupBallotInclusiveBitCount:
5948 case glslang::EOpSubgroupBallotExclusiveBitCount:
5949 case glslang::EOpSubgroupBallotFindLSB:
5950 case glslang::EOpSubgroupBallotFindMSB:
5951 builder.addCapability(spv::CapabilityGroupNonUniform);
5952 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5953 break;
5954 case glslang::EOpSubgroupShuffle:
5955 case glslang::EOpSubgroupShuffleXor:
5956 builder.addCapability(spv::CapabilityGroupNonUniform);
5957 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5958 break;
5959 case glslang::EOpSubgroupShuffleUp:
5960 case glslang::EOpSubgroupShuffleDown:
5961 builder.addCapability(spv::CapabilityGroupNonUniform);
5962 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5963 break;
5964 case glslang::EOpSubgroupAdd:
5965 case glslang::EOpSubgroupMul:
5966 case glslang::EOpSubgroupMin:
5967 case glslang::EOpSubgroupMax:
5968 case glslang::EOpSubgroupAnd:
5969 case glslang::EOpSubgroupOr:
5970 case glslang::EOpSubgroupXor:
5971 case glslang::EOpSubgroupInclusiveAdd:
5972 case glslang::EOpSubgroupInclusiveMul:
5973 case glslang::EOpSubgroupInclusiveMin:
5974 case glslang::EOpSubgroupInclusiveMax:
5975 case glslang::EOpSubgroupInclusiveAnd:
5976 case glslang::EOpSubgroupInclusiveOr:
5977 case glslang::EOpSubgroupInclusiveXor:
5978 case glslang::EOpSubgroupExclusiveAdd:
5979 case glslang::EOpSubgroupExclusiveMul:
5980 case glslang::EOpSubgroupExclusiveMin:
5981 case glslang::EOpSubgroupExclusiveMax:
5982 case glslang::EOpSubgroupExclusiveAnd:
5983 case glslang::EOpSubgroupExclusiveOr:
5984 case glslang::EOpSubgroupExclusiveXor:
5985 builder.addCapability(spv::CapabilityGroupNonUniform);
5986 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5987 break;
5988 case glslang::EOpSubgroupClusteredAdd:
5989 case glslang::EOpSubgroupClusteredMul:
5990 case glslang::EOpSubgroupClusteredMin:
5991 case glslang::EOpSubgroupClusteredMax:
5992 case glslang::EOpSubgroupClusteredAnd:
5993 case glslang::EOpSubgroupClusteredOr:
5994 case glslang::EOpSubgroupClusteredXor:
5995 builder.addCapability(spv::CapabilityGroupNonUniform);
5996 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5997 break;
5998 case glslang::EOpSubgroupQuadBroadcast:
5999 case glslang::EOpSubgroupQuadSwapHorizontal:
6000 case glslang::EOpSubgroupQuadSwapVertical:
6001 case glslang::EOpSubgroupQuadSwapDiagonal:
6002 builder.addCapability(spv::CapabilityGroupNonUniform);
6003 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6004 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006005#ifdef NV_EXTENSIONS
6006 case glslang::EOpSubgroupPartitionedAdd:
6007 case glslang::EOpSubgroupPartitionedMul:
6008 case glslang::EOpSubgroupPartitionedMin:
6009 case glslang::EOpSubgroupPartitionedMax:
6010 case glslang::EOpSubgroupPartitionedAnd:
6011 case glslang::EOpSubgroupPartitionedOr:
6012 case glslang::EOpSubgroupPartitionedXor:
6013 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6014 case glslang::EOpSubgroupPartitionedInclusiveMul:
6015 case glslang::EOpSubgroupPartitionedInclusiveMin:
6016 case glslang::EOpSubgroupPartitionedInclusiveMax:
6017 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6018 case glslang::EOpSubgroupPartitionedInclusiveOr:
6019 case glslang::EOpSubgroupPartitionedInclusiveXor:
6020 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6021 case glslang::EOpSubgroupPartitionedExclusiveMul:
6022 case glslang::EOpSubgroupPartitionedExclusiveMin:
6023 case glslang::EOpSubgroupPartitionedExclusiveMax:
6024 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6025 case glslang::EOpSubgroupPartitionedExclusiveOr:
6026 case glslang::EOpSubgroupPartitionedExclusiveXor:
6027 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6028 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6029 break;
6030#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006031 default: assert(0 && "Unhandled subgroup operation!");
6032 }
6033
6034 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6035 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6036 const bool isBool = typeProxy == glslang::EbtBool;
6037
6038 spv::Op opCode = spv::OpNop;
6039
6040 // Figure out which opcode to use.
6041 switch (op) {
6042 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6043 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6044 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6045 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6046 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6047 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6048 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6049 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6050 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6051 case glslang::EOpSubgroupBallotBitCount:
6052 case glslang::EOpSubgroupBallotInclusiveBitCount:
6053 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6054 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6055 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6056 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6057 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6058 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6059 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6060 case glslang::EOpSubgroupAdd:
6061 case glslang::EOpSubgroupInclusiveAdd:
6062 case glslang::EOpSubgroupExclusiveAdd:
6063 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006064#ifdef NV_EXTENSIONS
6065 case glslang::EOpSubgroupPartitionedAdd:
6066 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6067 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6068#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006069 if (isFloat) {
6070 opCode = spv::OpGroupNonUniformFAdd;
6071 } else {
6072 opCode = spv::OpGroupNonUniformIAdd;
6073 }
6074 break;
6075 case glslang::EOpSubgroupMul:
6076 case glslang::EOpSubgroupInclusiveMul:
6077 case glslang::EOpSubgroupExclusiveMul:
6078 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006079#ifdef NV_EXTENSIONS
6080 case glslang::EOpSubgroupPartitionedMul:
6081 case glslang::EOpSubgroupPartitionedInclusiveMul:
6082 case glslang::EOpSubgroupPartitionedExclusiveMul:
6083#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006084 if (isFloat) {
6085 opCode = spv::OpGroupNonUniformFMul;
6086 } else {
6087 opCode = spv::OpGroupNonUniformIMul;
6088 }
6089 break;
6090 case glslang::EOpSubgroupMin:
6091 case glslang::EOpSubgroupInclusiveMin:
6092 case glslang::EOpSubgroupExclusiveMin:
6093 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006094#ifdef NV_EXTENSIONS
6095 case glslang::EOpSubgroupPartitionedMin:
6096 case glslang::EOpSubgroupPartitionedInclusiveMin:
6097 case glslang::EOpSubgroupPartitionedExclusiveMin:
6098#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006099 if (isFloat) {
6100 opCode = spv::OpGroupNonUniformFMin;
6101 } else if (isUnsigned) {
6102 opCode = spv::OpGroupNonUniformUMin;
6103 } else {
6104 opCode = spv::OpGroupNonUniformSMin;
6105 }
6106 break;
6107 case glslang::EOpSubgroupMax:
6108 case glslang::EOpSubgroupInclusiveMax:
6109 case glslang::EOpSubgroupExclusiveMax:
6110 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006111#ifdef NV_EXTENSIONS
6112 case glslang::EOpSubgroupPartitionedMax:
6113 case glslang::EOpSubgroupPartitionedInclusiveMax:
6114 case glslang::EOpSubgroupPartitionedExclusiveMax:
6115#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006116 if (isFloat) {
6117 opCode = spv::OpGroupNonUniformFMax;
6118 } else if (isUnsigned) {
6119 opCode = spv::OpGroupNonUniformUMax;
6120 } else {
6121 opCode = spv::OpGroupNonUniformSMax;
6122 }
6123 break;
6124 case glslang::EOpSubgroupAnd:
6125 case glslang::EOpSubgroupInclusiveAnd:
6126 case glslang::EOpSubgroupExclusiveAnd:
6127 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006128#ifdef NV_EXTENSIONS
6129 case glslang::EOpSubgroupPartitionedAnd:
6130 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6131 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6132#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006133 if (isBool) {
6134 opCode = spv::OpGroupNonUniformLogicalAnd;
6135 } else {
6136 opCode = spv::OpGroupNonUniformBitwiseAnd;
6137 }
6138 break;
6139 case glslang::EOpSubgroupOr:
6140 case glslang::EOpSubgroupInclusiveOr:
6141 case glslang::EOpSubgroupExclusiveOr:
6142 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006143#ifdef NV_EXTENSIONS
6144 case glslang::EOpSubgroupPartitionedOr:
6145 case glslang::EOpSubgroupPartitionedInclusiveOr:
6146 case glslang::EOpSubgroupPartitionedExclusiveOr:
6147#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006148 if (isBool) {
6149 opCode = spv::OpGroupNonUniformLogicalOr;
6150 } else {
6151 opCode = spv::OpGroupNonUniformBitwiseOr;
6152 }
6153 break;
6154 case glslang::EOpSubgroupXor:
6155 case glslang::EOpSubgroupInclusiveXor:
6156 case glslang::EOpSubgroupExclusiveXor:
6157 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006158#ifdef NV_EXTENSIONS
6159 case glslang::EOpSubgroupPartitionedXor:
6160 case glslang::EOpSubgroupPartitionedInclusiveXor:
6161 case glslang::EOpSubgroupPartitionedExclusiveXor:
6162#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006163 if (isBool) {
6164 opCode = spv::OpGroupNonUniformLogicalXor;
6165 } else {
6166 opCode = spv::OpGroupNonUniformBitwiseXor;
6167 }
6168 break;
6169 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6170 case glslang::EOpSubgroupQuadSwapHorizontal:
6171 case glslang::EOpSubgroupQuadSwapVertical:
6172 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6173 default: assert(0 && "Unhandled subgroup operation!");
6174 }
6175
John Kessenich149afc32018-08-14 13:31:43 -06006176 // get the right Group Operation
6177 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006178 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006179 default:
6180 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006181 case glslang::EOpSubgroupBallotBitCount:
6182 case glslang::EOpSubgroupAdd:
6183 case glslang::EOpSubgroupMul:
6184 case glslang::EOpSubgroupMin:
6185 case glslang::EOpSubgroupMax:
6186 case glslang::EOpSubgroupAnd:
6187 case glslang::EOpSubgroupOr:
6188 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006189 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006190 break;
6191 case glslang::EOpSubgroupBallotInclusiveBitCount:
6192 case glslang::EOpSubgroupInclusiveAdd:
6193 case glslang::EOpSubgroupInclusiveMul:
6194 case glslang::EOpSubgroupInclusiveMin:
6195 case glslang::EOpSubgroupInclusiveMax:
6196 case glslang::EOpSubgroupInclusiveAnd:
6197 case glslang::EOpSubgroupInclusiveOr:
6198 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006199 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006200 break;
6201 case glslang::EOpSubgroupBallotExclusiveBitCount:
6202 case glslang::EOpSubgroupExclusiveAdd:
6203 case glslang::EOpSubgroupExclusiveMul:
6204 case glslang::EOpSubgroupExclusiveMin:
6205 case glslang::EOpSubgroupExclusiveMax:
6206 case glslang::EOpSubgroupExclusiveAnd:
6207 case glslang::EOpSubgroupExclusiveOr:
6208 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006209 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006210 break;
6211 case glslang::EOpSubgroupClusteredAdd:
6212 case glslang::EOpSubgroupClusteredMul:
6213 case glslang::EOpSubgroupClusteredMin:
6214 case glslang::EOpSubgroupClusteredMax:
6215 case glslang::EOpSubgroupClusteredAnd:
6216 case glslang::EOpSubgroupClusteredOr:
6217 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006218 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006219 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006220#ifdef NV_EXTENSIONS
6221 case glslang::EOpSubgroupPartitionedAdd:
6222 case glslang::EOpSubgroupPartitionedMul:
6223 case glslang::EOpSubgroupPartitionedMin:
6224 case glslang::EOpSubgroupPartitionedMax:
6225 case glslang::EOpSubgroupPartitionedAnd:
6226 case glslang::EOpSubgroupPartitionedOr:
6227 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006228 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006229 break;
6230 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6231 case glslang::EOpSubgroupPartitionedInclusiveMul:
6232 case glslang::EOpSubgroupPartitionedInclusiveMin:
6233 case glslang::EOpSubgroupPartitionedInclusiveMax:
6234 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6235 case glslang::EOpSubgroupPartitionedInclusiveOr:
6236 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006237 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006238 break;
6239 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6240 case glslang::EOpSubgroupPartitionedExclusiveMul:
6241 case glslang::EOpSubgroupPartitionedExclusiveMin:
6242 case glslang::EOpSubgroupPartitionedExclusiveMax:
6243 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6244 case glslang::EOpSubgroupPartitionedExclusiveOr:
6245 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006246 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006247 break;
6248#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006249 }
6250
John Kessenich149afc32018-08-14 13:31:43 -06006251 // build the instruction
6252 std::vector<spv::IdImmediate> spvGroupOperands;
6253
6254 // Every operation begins with the Execution Scope operand.
6255 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6256 spvGroupOperands.push_back(executionScope);
6257
6258 // Next, for all operations that use a Group Operation, push that as an operand.
6259 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006260 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006261 spvGroupOperands.push_back(groupOperand);
6262 }
6263
John Kessenich66011cb2018-03-06 16:12:04 -07006264 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006265 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6266 spv::IdImmediate operand = { true, *opIt };
6267 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006268 }
6269
6270 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006271 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006272 switch (op) {
6273 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006274 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6275 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6276 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6277 }
6278 if (directionId != spv::NoResult) {
6279 spv::IdImmediate direction = { true, directionId };
6280 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006281 }
6282
6283 return builder.createOp(opCode, typeId, spvGroupOperands);
6284}
6285
John Kessenich5e4b1242015-08-06 22:53:06 -06006286spv::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 -06006287{
John Kessenich66011cb2018-03-06 16:12:04 -07006288 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6289 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006290
John Kessenich140f3df2015-06-26 16:58:36 -06006291 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006292 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006293 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006294 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006295 spv::Id typeId0 = 0;
6296 if (consumedOperands > 0)
6297 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006298 spv::Id typeId1 = 0;
6299 if (consumedOperands > 1)
6300 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006301 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006302
6303 switch (op) {
6304 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006305 if (isFloat)
6306 libCall = spv::GLSLstd450FMin;
6307 else if (isUnsigned)
6308 libCall = spv::GLSLstd450UMin;
6309 else
6310 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006311 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006312 break;
6313 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006314 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006315 break;
6316 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006317 if (isFloat)
6318 libCall = spv::GLSLstd450FMax;
6319 else if (isUnsigned)
6320 libCall = spv::GLSLstd450UMax;
6321 else
6322 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006323 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006324 break;
6325 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006326 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006327 break;
6328 case glslang::EOpDot:
6329 opCode = spv::OpDot;
6330 break;
6331 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006332 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006333 break;
6334
6335 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006336 if (isFloat)
6337 libCall = spv::GLSLstd450FClamp;
6338 else if (isUnsigned)
6339 libCall = spv::GLSLstd450UClamp;
6340 else
6341 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006342 builder.promoteScalar(precision, operands.front(), operands[1]);
6343 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006344 break;
6345 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006346 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6347 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006348 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006349 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006350 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006351 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006352 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006353 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006354 break;
6355 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006356 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006357 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006358 break;
6359 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006360 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006361 builder.promoteScalar(precision, operands[0], operands[2]);
6362 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006363 break;
6364
6365 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006366 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006367 break;
6368 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006369 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006370 break;
6371 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006372 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006373 break;
6374 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006375 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006376 break;
6377 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006378 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006379 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006380 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006381#ifdef AMD_EXTENSIONS
6382 if (typeProxy == glslang::EbtFloat16)
6383 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6384#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006385 libCall = spv::GLSLstd450InterpolateAtSample;
6386 break;
6387 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006388#ifdef AMD_EXTENSIONS
6389 if (typeProxy == glslang::EbtFloat16)
6390 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6391#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006392 libCall = spv::GLSLstd450InterpolateAtOffset;
6393 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006394 case glslang::EOpAddCarry:
6395 opCode = spv::OpIAddCarry;
6396 typeId = builder.makeStructResultType(typeId0, typeId0);
6397 consumedOperands = 2;
6398 break;
6399 case glslang::EOpSubBorrow:
6400 opCode = spv::OpISubBorrow;
6401 typeId = builder.makeStructResultType(typeId0, typeId0);
6402 consumedOperands = 2;
6403 break;
6404 case glslang::EOpUMulExtended:
6405 opCode = spv::OpUMulExtended;
6406 typeId = builder.makeStructResultType(typeId0, typeId0);
6407 consumedOperands = 2;
6408 break;
6409 case glslang::EOpIMulExtended:
6410 opCode = spv::OpSMulExtended;
6411 typeId = builder.makeStructResultType(typeId0, typeId0);
6412 consumedOperands = 2;
6413 break;
6414 case glslang::EOpBitfieldExtract:
6415 if (isUnsigned)
6416 opCode = spv::OpBitFieldUExtract;
6417 else
6418 opCode = spv::OpBitFieldSExtract;
6419 break;
6420 case glslang::EOpBitfieldInsert:
6421 opCode = spv::OpBitFieldInsert;
6422 break;
6423
6424 case glslang::EOpFma:
6425 libCall = spv::GLSLstd450Fma;
6426 break;
6427 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006428 {
6429 libCall = spv::GLSLstd450FrexpStruct;
6430 assert(builder.isPointerType(typeId1));
6431 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006432 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006433#ifdef AMD_EXTENSIONS
6434 if (width == 16)
6435 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6436 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6437#endif
Rex Xu470026f2017-03-29 17:12:40 +08006438 if (builder.getNumComponents(operands[0]) == 1)
6439 frexpIntType = builder.makeIntegerType(width, true);
6440 else
6441 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6442 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6443 consumedOperands = 1;
6444 }
John Kessenich55e7d112015-11-15 21:33:39 -07006445 break;
6446 case glslang::EOpLdexp:
6447 libCall = spv::GLSLstd450Ldexp;
6448 break;
6449
Rex Xu574ab042016-04-14 16:53:07 +08006450 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006451 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006452
John Kessenich66011cb2018-03-06 16:12:04 -07006453 case glslang::EOpSubgroupBroadcast:
6454 case glslang::EOpSubgroupBallotBitExtract:
6455 case glslang::EOpSubgroupShuffle:
6456 case glslang::EOpSubgroupShuffleXor:
6457 case glslang::EOpSubgroupShuffleUp:
6458 case glslang::EOpSubgroupShuffleDown:
6459 case glslang::EOpSubgroupClusteredAdd:
6460 case glslang::EOpSubgroupClusteredMul:
6461 case glslang::EOpSubgroupClusteredMin:
6462 case glslang::EOpSubgroupClusteredMax:
6463 case glslang::EOpSubgroupClusteredAnd:
6464 case glslang::EOpSubgroupClusteredOr:
6465 case glslang::EOpSubgroupClusteredXor:
6466 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006467#ifdef NV_EXTENSIONS
6468 case glslang::EOpSubgroupPartitionedAdd:
6469 case glslang::EOpSubgroupPartitionedMul:
6470 case glslang::EOpSubgroupPartitionedMin:
6471 case glslang::EOpSubgroupPartitionedMax:
6472 case glslang::EOpSubgroupPartitionedAnd:
6473 case glslang::EOpSubgroupPartitionedOr:
6474 case glslang::EOpSubgroupPartitionedXor:
6475 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6476 case glslang::EOpSubgroupPartitionedInclusiveMul:
6477 case glslang::EOpSubgroupPartitionedInclusiveMin:
6478 case glslang::EOpSubgroupPartitionedInclusiveMax:
6479 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6480 case glslang::EOpSubgroupPartitionedInclusiveOr:
6481 case glslang::EOpSubgroupPartitionedInclusiveXor:
6482 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6483 case glslang::EOpSubgroupPartitionedExclusiveMul:
6484 case glslang::EOpSubgroupPartitionedExclusiveMin:
6485 case glslang::EOpSubgroupPartitionedExclusiveMax:
6486 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6487 case glslang::EOpSubgroupPartitionedExclusiveOr:
6488 case glslang::EOpSubgroupPartitionedExclusiveXor:
6489#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006490 return createSubgroupOperation(op, typeId, operands, typeProxy);
6491
Rex Xu9d93a232016-05-05 12:30:44 +08006492#ifdef AMD_EXTENSIONS
6493 case glslang::EOpSwizzleInvocations:
6494 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6495 libCall = spv::SwizzleInvocationsAMD;
6496 break;
6497 case glslang::EOpSwizzleInvocationsMasked:
6498 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6499 libCall = spv::SwizzleInvocationsMaskedAMD;
6500 break;
6501 case glslang::EOpWriteInvocation:
6502 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6503 libCall = spv::WriteInvocationAMD;
6504 break;
6505
6506 case glslang::EOpMin3:
6507 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6508 if (isFloat)
6509 libCall = spv::FMin3AMD;
6510 else {
6511 if (isUnsigned)
6512 libCall = spv::UMin3AMD;
6513 else
6514 libCall = spv::SMin3AMD;
6515 }
6516 break;
6517 case glslang::EOpMax3:
6518 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6519 if (isFloat)
6520 libCall = spv::FMax3AMD;
6521 else {
6522 if (isUnsigned)
6523 libCall = spv::UMax3AMD;
6524 else
6525 libCall = spv::SMax3AMD;
6526 }
6527 break;
6528 case glslang::EOpMid3:
6529 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6530 if (isFloat)
6531 libCall = spv::FMid3AMD;
6532 else {
6533 if (isUnsigned)
6534 libCall = spv::UMid3AMD;
6535 else
6536 libCall = spv::SMid3AMD;
6537 }
6538 break;
6539
6540 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006541 if (typeProxy == glslang::EbtFloat16)
6542 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006543 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6544 libCall = spv::InterpolateAtVertexAMD;
6545 break;
6546#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006547 case glslang::EOpBarrier:
6548 {
6549 // This is for the extended controlBarrier function, with four operands.
6550 // The unextended barrier() goes through createNoArgOperation.
6551 assert(operands.size() == 4);
6552 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6553 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6554 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6555 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6556 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6557 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6558 }
6559 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6560 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6561 }
6562 return 0;
6563 }
6564 break;
6565 case glslang::EOpMemoryBarrier:
6566 {
6567 // This is for the extended memoryBarrier function, with three operands.
6568 // The unextended memoryBarrier() goes through createNoArgOperation.
6569 assert(operands.size() == 3);
6570 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6571 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6572 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6573 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6574 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6575 }
6576 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6577 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6578 }
6579 return 0;
6580 }
6581 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006582 default:
6583 return 0;
6584 }
6585
6586 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006587 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006588 // Use an extended instruction from the standard library.
6589 // Construct the call arguments, without modifying the original operands vector.
6590 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6591 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006592 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006593 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006594 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006595 case 0:
6596 // should all be handled by visitAggregate and createNoArgOperation
6597 assert(0);
6598 return 0;
6599 case 1:
6600 // should all be handled by createUnaryOperation
6601 assert(0);
6602 return 0;
6603 case 2:
6604 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6605 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006606 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006607 // anything 3 or over doesn't have l-value operands, so all should be consumed
6608 assert(consumedOperands == operands.size());
6609 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006610 break;
6611 }
6612 }
6613
John Kessenich55e7d112015-11-15 21:33:39 -07006614 // Decode the return types that were structures
6615 switch (op) {
6616 case glslang::EOpAddCarry:
6617 case glslang::EOpSubBorrow:
6618 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6619 id = builder.createCompositeExtract(id, typeId0, 0);
6620 break;
6621 case glslang::EOpUMulExtended:
6622 case glslang::EOpIMulExtended:
6623 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6624 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6625 break;
6626 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006627 {
6628 assert(operands.size() == 2);
6629 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6630 // "exp" is floating-point type (from HLSL intrinsic)
6631 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6632 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6633 builder.createStore(member1, operands[1]);
6634 } else
6635 // "exp" is integer type (from GLSL built-in function)
6636 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6637 id = builder.createCompositeExtract(id, typeId0, 0);
6638 }
John Kessenich55e7d112015-11-15 21:33:39 -07006639 break;
6640 default:
6641 break;
6642 }
6643
John Kessenich32cfd492016-02-02 12:37:46 -07006644 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006645}
6646
Rex Xu9d93a232016-05-05 12:30:44 +08006647// Intrinsics with no arguments (or no return value, and no precision).
6648spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006649{
Jeff Bolz36831c92018-09-05 10:11:41 -05006650 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6651 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006652
6653 switch (op) {
6654 case glslang::EOpEmitVertex:
6655 builder.createNoResultOp(spv::OpEmitVertex);
6656 return 0;
6657 case glslang::EOpEndPrimitive:
6658 builder.createNoResultOp(spv::OpEndPrimitive);
6659 return 0;
6660 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006661 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006662 if (glslangIntermediate->usingVulkanMemoryModel()) {
6663 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6664 spv::MemorySemanticsOutputMemoryKHRMask |
6665 spv::MemorySemanticsAcquireReleaseMask);
6666 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6667 } else {
6668 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6669 }
John Kessenich82979362017-12-11 04:02:24 -07006670 } else {
6671 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6672 spv::MemorySemanticsWorkgroupMemoryMask |
6673 spv::MemorySemanticsAcquireReleaseMask);
6674 }
John Kessenich140f3df2015-06-26 16:58:36 -06006675 return 0;
6676 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006677 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6678 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006679 return 0;
6680 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006681 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6682 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006683 return 0;
6684 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006685 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6686 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006687 return 0;
6688 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006689 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6690 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006691 return 0;
6692 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006693 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6694 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006695 return 0;
6696 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006697 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6698 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006699 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006700 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006701 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006702 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006703 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006704 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006705 case glslang::EOpDeviceMemoryBarrier:
6706 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6707 spv::MemorySemanticsImageMemoryMask |
6708 spv::MemorySemanticsAcquireReleaseMask);
6709 return 0;
6710 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6711 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6712 spv::MemorySemanticsImageMemoryMask |
6713 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006714 return 0;
6715 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006716 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6717 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006718 return 0;
6719 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006720 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6721 spv::MemorySemanticsWorkgroupMemoryMask |
6722 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006723 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006724 case glslang::EOpSubgroupBarrier:
6725 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6726 spv::MemorySemanticsAcquireReleaseMask);
6727 return spv::NoResult;
6728 case glslang::EOpSubgroupMemoryBarrier:
6729 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6730 spv::MemorySemanticsAcquireReleaseMask);
6731 return spv::NoResult;
6732 case glslang::EOpSubgroupMemoryBarrierBuffer:
6733 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6734 spv::MemorySemanticsAcquireReleaseMask);
6735 return spv::NoResult;
6736 case glslang::EOpSubgroupMemoryBarrierImage:
6737 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6738 spv::MemorySemanticsAcquireReleaseMask);
6739 return spv::NoResult;
6740 case glslang::EOpSubgroupMemoryBarrierShared:
6741 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6742 spv::MemorySemanticsAcquireReleaseMask);
6743 return spv::NoResult;
6744 case glslang::EOpSubgroupElect: {
6745 std::vector<spv::Id> operands;
6746 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6747 }
Rex Xu9d93a232016-05-05 12:30:44 +08006748#ifdef AMD_EXTENSIONS
6749 case glslang::EOpTime:
6750 {
6751 std::vector<spv::Id> args; // Dummy arguments
6752 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6753 return builder.setPrecision(id, precision);
6754 }
6755#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006756 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006757 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006758 return 0;
6759 }
6760}
6761
6762spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6763{
John Kessenich2f273362015-07-18 22:34:27 -06006764 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006765 spv::Id id;
6766 if (symbolValues.end() != iter) {
6767 id = iter->second;
6768 return id;
6769 }
6770
6771 // it was not found, create it
6772 id = createSpvVariable(symbol);
6773 symbolValues[symbol->getId()] = id;
6774
Rex Xuc884b4a2016-06-29 15:03:44 +08006775 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006776 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6777 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6778 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006779 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006780 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006781 if (symbol->getQualifier().hasIndex())
6782 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6783 if (symbol->getQualifier().hasComponent())
6784 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006785 // atomic counters use this:
6786 if (symbol->getQualifier().hasOffset())
6787 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006788 }
6789
scygan2c864272016-05-18 18:09:17 +02006790 if (symbol->getQualifier().hasLocation())
6791 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006792 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006793 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006794 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006795 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006796 }
John Kessenich140f3df2015-06-26 16:58:36 -06006797 if (symbol->getQualifier().hasSet())
6798 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006799 else if (IsDescriptorResource(symbol->getType())) {
6800 // default to 0
6801 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6802 }
John Kessenich140f3df2015-06-26 16:58:36 -06006803 if (symbol->getQualifier().hasBinding())
6804 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006805 if (symbol->getQualifier().hasAttachment())
6806 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006807 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006808 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006809 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006810 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006811 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006812 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006813 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6814 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6815 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6816 }
6817 if (symbol->getQualifier().hasXfbOffset())
6818 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006819 }
6820
Rex Xu1da878f2016-02-21 20:59:01 +08006821 if (symbol->getType().isImage()) {
6822 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05006823 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08006824 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006825 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006826 }
6827
John Kessenich140f3df2015-06-26 16:58:36 -06006828 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006829 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006830 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006831 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006832
John Kessenich5611c6d2018-04-05 11:25:02 -06006833 // nonuniform
6834 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6835
John Kessenichecba76f2017-01-06 00:34:48 -07006836#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006837 if (builtIn == spv::BuiltInSampleMask) {
6838 spv::Decoration decoration;
6839 // GL_NV_sample_mask_override_coverage extension
6840 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006841 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006842 else
6843 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006844 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006845 if (decoration != spv::DecorationMax) {
6846 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6847 }
6848 }
chaoc771d89f2017-01-13 01:10:53 -08006849 else if (builtIn == spv::BuiltInLayer) {
6850 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006851 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006852 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006853 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6854 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6855 }
John Kessenichb41bff62017-08-11 13:07:17 -06006856 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006857 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6858 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006859 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6860 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6861 }
6862 }
6863
chaoc6e5acae2016-12-20 13:28:52 -08006864 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006865 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006866 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006867 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6868 }
Chao Chen9eada4b2018-09-19 11:39:56 -07006869 if (symbol->getQualifier().pervertexNV) {
6870 builder.addDecoration(id, spv::DecorationPerVertexNV);
6871 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
6872 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
6873 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006874#endif
6875
John Kessenich5d610ee2018-03-07 18:05:55 -07006876 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6877 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6878 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6879 symbol->getType().getQualifier().semanticName);
6880 }
6881
John Kessenich140f3df2015-06-26 16:58:36 -06006882 return id;
6883}
6884
John Kessenich55e7d112015-11-15 21:33:39 -07006885// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006886// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006887//
6888// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6889//
6890// Recursively walk the nodes. The nodes form a tree whose leaves are
6891// regular constants, which themselves are trees that createSpvConstant()
6892// recursively walks. So, this function walks the "top" of the tree:
6893// - emit specialization constant-building instructions for specConstant
6894// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006895spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006896{
John Kessenich7cc0e282016-03-20 00:46:02 -06006897 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006898
qining4f4bb812016-04-03 23:55:17 -04006899 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006900 if (! node.getQualifier().specConstant) {
6901 // hand off to the non-spec-constant path
6902 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6903 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006904 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006905 nextConst, false);
6906 }
6907
6908 // We now know we have a specialization constant to build
6909
John Kessenichd94c0032016-05-30 19:29:40 -06006910 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006911 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6912 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6913 std::vector<spv::Id> dimConstId;
6914 for (int dim = 0; dim < 3; ++dim) {
6915 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6916 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006917 if (specConst) {
6918 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6919 glslangIntermediate->getLocalSizeSpecId(dim));
6920 }
qining4f4bb812016-04-03 23:55:17 -04006921 }
6922 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6923 }
6924
6925 // An AST node labelled as specialization constant should be a symbol node.
6926 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6927 if (auto* sn = node.getAsSymbolNode()) {
6928 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006929 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6930 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6931 // will set the builder into spec constant op instruction generating mode.
6932 sub_tree->traverse(this);
6933 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006934 } else if (auto* const_union_array = &sn->getConstArray()){
6935 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006936 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6937 builder.addName(id, sn->getName().c_str());
6938 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006939 }
6940 }
qining4f4bb812016-04-03 23:55:17 -04006941
6942 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6943 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006944 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006945 exit(1);
6946 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006947}
6948
John Kessenich140f3df2015-06-26 16:58:36 -06006949// Use 'consts' as the flattened glslang source of scalar constants to recursively
6950// build the aggregate SPIR-V constant.
6951//
6952// If there are not enough elements present in 'consts', 0 will be substituted;
6953// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6954//
qining08408382016-03-21 09:51:37 -04006955spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006956{
6957 // vector of constants for SPIR-V
6958 std::vector<spv::Id> spvConsts;
6959
6960 // Type is used for struct and array constants
6961 spv::Id typeId = convertGlslangToSpvType(glslangType);
6962
6963 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006964 glslang::TType elementType(glslangType, 0);
6965 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006966 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006967 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006968 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006969 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006970 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006971 } else if (glslangType.getStruct()) {
6972 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6973 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006974 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006975 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006976 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6977 bool zero = nextConst >= consts.size();
6978 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006979 case glslang::EbtInt8:
6980 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6981 break;
6982 case glslang::EbtUint8:
6983 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6984 break;
6985 case glslang::EbtInt16:
6986 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6987 break;
6988 case glslang::EbtUint16:
6989 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6990 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006991 case glslang::EbtInt:
6992 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6993 break;
6994 case glslang::EbtUint:
6995 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6996 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006997 case glslang::EbtInt64:
6998 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6999 break;
7000 case glslang::EbtUint64:
7001 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7002 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007003 case glslang::EbtFloat:
7004 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7005 break;
7006 case glslang::EbtDouble:
7007 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7008 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007009 case glslang::EbtFloat16:
7010 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7011 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007012 case glslang::EbtBool:
7013 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7014 break;
7015 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007016 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007017 break;
7018 }
7019 ++nextConst;
7020 }
7021 } else {
7022 // we have a non-aggregate (scalar) constant
7023 bool zero = nextConst >= consts.size();
7024 spv::Id scalar = 0;
7025 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007026 case glslang::EbtInt8:
7027 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7028 break;
7029 case glslang::EbtUint8:
7030 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7031 break;
7032 case glslang::EbtInt16:
7033 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7034 break;
7035 case glslang::EbtUint16:
7036 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7037 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007038 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007039 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007040 break;
7041 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007042 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007043 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007044 case glslang::EbtInt64:
7045 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7046 break;
7047 case glslang::EbtUint64:
7048 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7049 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007050 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007051 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007052 break;
7053 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007054 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007055 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007056 case glslang::EbtFloat16:
7057 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7058 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007059 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007060 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007061 break;
7062 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007063 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007064 break;
7065 }
7066 ++nextConst;
7067 return scalar;
7068 }
7069
7070 return builder.makeCompositeConstant(typeId, spvConsts);
7071}
7072
John Kessenich7c1aa102015-10-15 13:29:11 -06007073// Return true if the node is a constant or symbol whose reading has no
7074// non-trivial observable cost or effect.
7075bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7076{
7077 // don't know what this is
7078 if (node == nullptr)
7079 return false;
7080
7081 // a constant is safe
7082 if (node->getAsConstantUnion() != nullptr)
7083 return true;
7084
7085 // not a symbol means non-trivial
7086 if (node->getAsSymbolNode() == nullptr)
7087 return false;
7088
7089 // a symbol, depends on what's being read
7090 switch (node->getType().getQualifier().storage) {
7091 case glslang::EvqTemporary:
7092 case glslang::EvqGlobal:
7093 case glslang::EvqIn:
7094 case glslang::EvqInOut:
7095 case glslang::EvqConst:
7096 case glslang::EvqConstReadOnly:
7097 case glslang::EvqUniform:
7098 return true;
7099 default:
7100 return false;
7101 }
qining25262b32016-05-06 17:25:16 -04007102}
John Kessenich7c1aa102015-10-15 13:29:11 -06007103
7104// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007105// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007106// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007107// Return true if trivial.
7108bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7109{
7110 if (node == nullptr)
7111 return false;
7112
John Kessenich84cc15f2017-05-24 16:44:47 -06007113 // count non scalars as trivial, as well as anything coming from HLSL
7114 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007115 return true;
7116
John Kessenich7c1aa102015-10-15 13:29:11 -06007117 // symbols and constants are trivial
7118 if (isTrivialLeaf(node))
7119 return true;
7120
7121 // otherwise, it needs to be a simple operation or one or two leaf nodes
7122
7123 // not a simple operation
7124 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7125 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7126 if (binaryNode == nullptr && unaryNode == nullptr)
7127 return false;
7128
7129 // not on leaf nodes
7130 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7131 return false;
7132
7133 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7134 return false;
7135 }
7136
7137 switch (node->getAsOperator()->getOp()) {
7138 case glslang::EOpLogicalNot:
7139 case glslang::EOpConvIntToBool:
7140 case glslang::EOpConvUintToBool:
7141 case glslang::EOpConvFloatToBool:
7142 case glslang::EOpConvDoubleToBool:
7143 case glslang::EOpEqual:
7144 case glslang::EOpNotEqual:
7145 case glslang::EOpLessThan:
7146 case glslang::EOpGreaterThan:
7147 case glslang::EOpLessThanEqual:
7148 case glslang::EOpGreaterThanEqual:
7149 case glslang::EOpIndexDirect:
7150 case glslang::EOpIndexDirectStruct:
7151 case glslang::EOpLogicalXor:
7152 case glslang::EOpAny:
7153 case glslang::EOpAll:
7154 return true;
7155 default:
7156 return false;
7157 }
7158}
7159
7160// Emit short-circuiting code, where 'right' is never evaluated unless
7161// the left side is true (for &&) or false (for ||).
7162spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7163{
7164 spv::Id boolTypeId = builder.makeBoolType();
7165
7166 // emit left operand
7167 builder.clearAccessChain();
7168 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007169 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007170
7171 // Operands to accumulate OpPhi operands
7172 std::vector<spv::Id> phiOperands;
7173 // accumulate left operand's phi information
7174 phiOperands.push_back(leftId);
7175 phiOperands.push_back(builder.getBuildPoint()->getId());
7176
7177 // Make the two kinds of operation symmetric with a "!"
7178 // || => emit "if (! left) result = right"
7179 // && => emit "if ( left) result = right"
7180 //
7181 // TODO: this runtime "not" for || could be avoided by adding functionality
7182 // to 'builder' to have an "else" without an "then"
7183 if (op == glslang::EOpLogicalOr)
7184 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7185
7186 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007187 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007188
7189 // emit right operand as the "then" part of the "if"
7190 builder.clearAccessChain();
7191 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007192 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007193
7194 // accumulate left operand's phi information
7195 phiOperands.push_back(rightId);
7196 phiOperands.push_back(builder.getBuildPoint()->getId());
7197
7198 // finish the "if"
7199 ifBuilder.makeEndIf();
7200
7201 // phi together the two results
7202 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7203}
7204
Frank Henigman541f7bb2018-01-16 00:18:26 -05007205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007206// Return type Id of the imported set of extended instructions corresponds to the name.
7207// Import this set if it has not been imported yet.
7208spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7209{
7210 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7211 return extBuiltinMap[name];
7212 else {
Rex Xu51596642016-09-21 18:56:12 +08007213 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007214 spv::Id extBuiltins = builder.import(name);
7215 extBuiltinMap[name] = extBuiltins;
7216 return extBuiltins;
7217 }
7218}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007219#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007220
John Kessenich140f3df2015-06-26 16:58:36 -06007221}; // end anonymous namespace
7222
7223namespace glslang {
7224
John Kessenich68d78fd2015-07-12 19:28:10 -06007225void GetSpirvVersion(std::string& version)
7226{
John Kessenich9e55f632015-07-15 10:03:39 -06007227 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007228 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007229 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007230 version = buf;
7231}
7232
John Kessenicha372a3e2017-11-02 22:32:14 -06007233// For low-order part of the generator's magic number. Bump up
7234// when there is a change in the style (e.g., if SSA form changes,
7235// or a different instruction sequence to do something gets used).
7236int GetSpirvGeneratorVersion()
7237{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007238 // return 1; // start
7239 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007240 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007241 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007242 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007243 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7244 // versions 4 and 6 each generate OpArrayLength as it has long been done
7245 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007246}
7247
John Kessenich140f3df2015-06-26 16:58:36 -06007248// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007249void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007250{
7251 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007252 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007253 if (out.fail())
7254 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007255 for (int i = 0; i < (int)spirv.size(); ++i) {
7256 unsigned int word = spirv[i];
7257 out.write((const char*)&word, 4);
7258 }
7259 out.close();
7260}
7261
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007262// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007263void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007264{
7265 std::ofstream out;
7266 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007267 if (out.fail())
7268 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007269 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007270 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007271 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007272 if (varName != nullptr) {
7273 out << "\t #pragma once" << std::endl;
7274 out << "const uint32_t " << varName << "[] = {" << std::endl;
7275 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007276 const int WORDS_PER_LINE = 8;
7277 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7278 out << "\t";
7279 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7280 const unsigned int word = spirv[i + j];
7281 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7282 if (i + j + 1 < (int)spirv.size()) {
7283 out << ",";
7284 }
7285 }
7286 out << std::endl;
7287 }
Flavio15017db2017-02-15 14:29:33 -08007288 if (varName != nullptr) {
7289 out << "};";
7290 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007291 out.close();
7292}
7293
John Kessenich140f3df2015-06-26 16:58:36 -06007294//
7295// Set up the glslang traversal
7296//
John Kessenich4e11b612018-08-30 16:56:59 -06007297void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007298{
Lei Zhang17535f72016-05-04 15:55:59 -04007299 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007300 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007301}
7302
John Kessenich4e11b612018-08-30 16:56:59 -06007303void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007304 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007305{
John Kessenich140f3df2015-06-26 16:58:36 -06007306 TIntermNode* root = intermediate.getTreeRoot();
7307
7308 if (root == 0)
7309 return;
7310
John Kessenich4e11b612018-08-30 16:56:59 -06007311 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007312 if (options == nullptr)
7313 options = &defaultOptions;
7314
John Kessenich4e11b612018-08-30 16:56:59 -06007315 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007316
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007317 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007318 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007319 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007320 it.dumpSpv(spirv);
7321
GregFfb03a552018-03-29 11:49:14 -06007322#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007323 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7324 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007325 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007326 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007327
John Kessenich4e11b612018-08-30 16:56:59 -06007328 if (options->validate)
7329 SpirvToolsValidate(intermediate, spirv, logger);
7330
John Kessenich717c80a2018-08-23 15:17:10 -06007331 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007332 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007333
GregFcd1f1692017-09-21 18:40:22 -06007334#endif
7335
John Kessenich4e11b612018-08-30 16:56:59 -06007336 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007337}
7338
7339}; // end namespace glslang