blob: e1ae7b40cb448ed31d73eaf61009406b4d8a05cd [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700197#ifdef NV_EXTENSIONS
198 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
199#endif
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
229 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800230 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600231
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600233 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700235 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
237 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700239 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNVX;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNVX;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNVX;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNVX;
283 case EShLangMissNV: return spv::ExecutionModelMissNVX;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNVX;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
341#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600342 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 break;
345 }
346 }
347
John Kessenich4016e382016-07-15 11:53:56 -0600348 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600349}
350
Rex Xu1da878f2016-02-21 20:59:01 +0800351// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500352void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800353{
Jeff Bolz36831c92018-09-05 10:11:41 -0500354 if (!useVulkanMemoryModel) {
355 if (qualifier.coherent)
356 memory.push_back(spv::DecorationCoherent);
357 if (qualifier.volatil) {
358 memory.push_back(spv::DecorationVolatile);
359 memory.push_back(spv::DecorationCoherent);
360 }
John Kessenich14b85d32018-06-04 15:36:03 -0600361 }
Rex Xu1da878f2016-02-21 20:59:01 +0800362 if (qualifier.restrict)
363 memory.push_back(spv::DecorationRestrict);
364 if (qualifier.readonly)
365 memory.push_back(spv::DecorationNonWritable);
366 if (qualifier.writeonly)
367 memory.push_back(spv::DecorationNonReadable);
368}
369
John Kessenich140f3df2015-06-26 16:58:36 -0600370// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700371spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
373 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700374 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600375 case glslang::ElmRowMajor:
376 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700377 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600378 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 default:
380 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 } else {
384 switch (type.getBasicType()) {
385 default:
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 break;
388 case glslang::EbtBlock:
389 switch (type.getQualifier().storage) {
390 case glslang::EvqUniform:
391 case glslang::EvqBuffer:
392 switch (type.getQualifier().layoutPacking) {
393 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600394 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
395 default:
John Kessenich4016e382016-07-15 11:53:56 -0600396 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 }
398 case glslang::EvqVaryingIn:
399 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700400 if (type.getQualifier().isTaskMemory()) {
401 switch (type.getQualifier().layoutPacking) {
402 case glslang::ElpShared: return spv::DecorationGLSLShared;
403 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
404 default: break;
405 }
406 } else {
407 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
408 }
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700410#ifdef NV_EXTENSIONS
411 case glslang::EvqPayloadNV:
412 case glslang::EvqPayloadInNV:
413 case glslang::EvqHitAttrNV:
414 return spv::DecorationMax;
415#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600416 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700417 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 }
420 }
421 }
422}
423
424// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600425// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700426// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800427spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600428{
Rex Xubbceed72016-05-21 09:40:44 +0800429 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700430 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800432 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700433 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600435 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800436#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800437 else if (qualifier.explicitInterp) {
438 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800439 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800440 }
Rex Xu9d93a232016-05-05 12:30:44 +0800441#endif
Rex Xubbceed72016-05-21 09:40:44 +0800442 else
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800444}
445
446// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600447// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800448// should be applied.
449spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
450{
451 if (qualifier.patch)
452 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700453 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600454 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700455 else if (qualifier.sample) {
456 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600457 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700458 } else
John Kessenich4016e382016-07-15 11:53:56 -0600459 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600460}
461
John Kessenich92187592016-02-01 13:45:25 -0700462// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700463spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600464{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700465 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600466 return spv::DecorationInvariant;
467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600469}
470
qining9220dbb2016-05-04 17:34:38 -0400471// If glslang type is noContraction, return SPIR-V NoContraction decoration.
472spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
473{
474 if (qualifier.noContraction)
475 return spv::DecorationNoContraction;
476 else
John Kessenich4016e382016-07-15 11:53:56 -0600477 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400478}
479
John Kessenich5611c6d2018-04-05 11:25:02 -0600480// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
481spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
482{
483 if (qualifier.isNonUniform()) {
484 builder.addExtension("SPV_EXT_descriptor_indexing");
485 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
486 return spv::DecorationNonUniformEXT;
487 } else
488 return spv::DecorationMax;
489}
490
Jeff Bolz36831c92018-09-05 10:11:41 -0500491spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
492{
493 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
494 return spv::MemoryAccessMaskNone;
495 }
496 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
497 if (coherentFlags.volatil ||
498 coherentFlags.coherent ||
499 coherentFlags.devicecoherent ||
500 coherentFlags.queuefamilycoherent ||
501 coherentFlags.workgroupcoherent ||
502 coherentFlags.subgroupcoherent) {
503 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
504 spv::MemoryAccessMakePointerVisibleKHRMask;
505 }
506 if (coherentFlags.nonprivate) {
507 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
508 }
509 if (coherentFlags.volatil) {
510 mask = mask | spv::MemoryAccessVolatileMask;
511 }
512 if (mask != spv::MemoryAccessMaskNone) {
513 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
514 }
515 return mask;
516}
517
518spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
519{
520 if (!glslangIntermediate->usingVulkanMemoryModel()) {
521 return spv::ImageOperandsMaskNone;
522 }
523 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
524 if (coherentFlags.volatil ||
525 coherentFlags.coherent ||
526 coherentFlags.devicecoherent ||
527 coherentFlags.queuefamilycoherent ||
528 coherentFlags.workgroupcoherent ||
529 coherentFlags.subgroupcoherent) {
530 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
531 spv::ImageOperandsMakeTexelVisibleKHRMask;
532 }
533 if (coherentFlags.nonprivate) {
534 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
535 }
536 if (coherentFlags.volatil) {
537 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
538 }
539 if (mask != spv::ImageOperandsMaskNone) {
540 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
541 }
542 return mask;
543}
544
545spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
546{
547 spv::Builder::AccessChain::CoherentFlags flags;
548 flags.coherent = type.getQualifier().coherent;
549 flags.devicecoherent = type.getQualifier().devicecoherent;
550 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
551 // shared variables are implicitly workgroupcoherent in GLSL.
552 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
553 type.getQualifier().storage == glslang::EvqShared;
554 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
555 // *coherent variables are implicitly nonprivate in GLSL
556 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500557 flags.subgroupcoherent ||
558 flags.workgroupcoherent ||
559 flags.queuefamilycoherent ||
560 flags.devicecoherent ||
561 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500562 flags.volatil = type.getQualifier().volatil;
563 flags.isImage = type.getBasicType() == glslang::EbtSampler;
564 return flags;
565}
566
567spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
568{
569 spv::Scope scope;
570 if (coherentFlags.coherent) {
571 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
572 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
573 } else if (coherentFlags.devicecoherent) {
574 scope = spv::ScopeDevice;
575 } else if (coherentFlags.queuefamilycoherent) {
576 scope = spv::ScopeQueueFamilyKHR;
577 } else if (coherentFlags.workgroupcoherent) {
578 scope = spv::ScopeWorkgroup;
579 } else if (coherentFlags.subgroupcoherent) {
580 scope = spv::ScopeSubgroup;
581 } else {
582 scope = spv::ScopeMax;
583 }
584 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
585 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
586 }
587 return scope;
588}
589
David Netoa901ffe2016-06-08 14:11:40 +0100590// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
591// associated capabilities when required. For some built-in variables, a capability
592// is generated only when using the variable in an executable instruction, but not when
593// just declaring a struct member variable with it. This is true for PointSize,
594// ClipDistance, and CullDistance.
595spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600596{
597 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700598 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600599 // Defer adding the capability until the built-in is actually used.
600 if (! memberDeclaration) {
601 switch (glslangIntermediate->getStage()) {
602 case EShLangGeometry:
603 builder.addCapability(spv::CapabilityGeometryPointSize);
604 break;
605 case EShLangTessControl:
606 case EShLangTessEvaluation:
607 builder.addCapability(spv::CapabilityTessellationPointSize);
608 break;
609 default:
610 break;
611 }
John Kessenich92187592016-02-01 13:45:25 -0700612 }
613 return spv::BuiltInPointSize;
614
John Kessenichebb50532016-05-16 19:22:05 -0600615 // These *Distance capabilities logically belong here, but if the member is declared and
616 // then never used, consumers of SPIR-V prefer the capability not be declared.
617 // They are now generated when used, rather than here when declared.
618 // Potentially, the specification should be more clear what the minimum
619 // use needed is to trigger the capability.
620 //
John Kessenich92187592016-02-01 13:45:25 -0700621 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100622 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800623 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700624 return spv::BuiltInClipDistance;
625
626 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInCullDistance;
630
631 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600632 builder.addCapability(spv::CapabilityMultiViewport);
633 if (glslangIntermediate->getStage() == EShLangVertex ||
634 glslangIntermediate->getStage() == EShLangTessControl ||
635 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800636
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
638 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800639 }
John Kessenich92187592016-02-01 13:45:25 -0700640 return spv::BuiltInViewportIndex;
641
John Kessenich5e801132016-02-15 11:09:46 -0700642 case glslang::EbvSampleId:
643 builder.addCapability(spv::CapabilitySampleRateShading);
644 return spv::BuiltInSampleId;
645
646 case glslang::EbvSamplePosition:
647 builder.addCapability(spv::CapabilitySampleRateShading);
648 return spv::BuiltInSamplePosition;
649
650 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700651 return spv::BuiltInSampleMask;
652
John Kessenich78a45572016-07-08 14:05:15 -0600653 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700654#ifdef NV_EXTENSIONS
655 if (glslangIntermediate->getStage() == EShLangMeshNV) {
656 return spv::BuiltInLayer;
657 }
658#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600659 builder.addCapability(spv::CapabilityGeometry);
660 if (glslangIntermediate->getStage() == EShLangVertex ||
661 glslangIntermediate->getStage() == EShLangTessControl ||
662 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800663
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
665 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800666 }
John Kessenich78a45572016-07-08 14:05:15 -0600667 return spv::BuiltInLayer;
668
John Kessenich140f3df2015-06-26 16:58:36 -0600669 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600670 case glslang::EbvVertexId: return spv::BuiltInVertexId;
671 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700672 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
673 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800674
John Kessenichda581a22015-10-14 14:10:30 -0600675 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700676 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800677 builder.addCapability(spv::CapabilityDrawParameters);
678 return spv::BuiltInBaseVertex;
679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
690 case glslang::EbvPrimitiveId:
691 if (glslangIntermediate->getStage() == EShLangFragment)
692 builder.addCapability(spv::CapabilityGeometry);
693 return spv::BuiltInPrimitiveId;
694
Rex Xu37cdcee2017-06-29 17:46:34 +0800695 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800696 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
697 builder.addCapability(spv::CapabilityStencilExportEXT);
698 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800699
John Kessenich140f3df2015-06-26 16:58:36 -0600700 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600701 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
702 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
703 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
704 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
705 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
706 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
707 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600708 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
709 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
710 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
711 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
712 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
713 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
714 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
715 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800716
Rex Xu574ab042016-04-14 16:53:07 +0800717 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800718 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800719 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
720 return spv::BuiltInSubgroupSize;
721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupLocalInvocationId;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupEqMaskKHR;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupGeMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGtMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupLeMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLtMaskKHR;
751
John Kessenich66011cb2018-03-06 16:12:04 -0700752 case glslang::EbvNumSubgroups:
753 builder.addCapability(spv::CapabilityGroupNonUniform);
754 return spv::BuiltInNumSubgroups;
755
756 case glslang::EbvSubgroupID:
757 builder.addCapability(spv::CapabilityGroupNonUniform);
758 return spv::BuiltInSubgroupId;
759
760 case glslang::EbvSubgroupSize2:
761 builder.addCapability(spv::CapabilityGroupNonUniform);
762 return spv::BuiltInSubgroupSize;
763
764 case glslang::EbvSubgroupInvocation2:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInSubgroupLocalInvocationId;
767
768 case glslang::EbvSubgroupEqMask2:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
771 return spv::BuiltInSubgroupEqMask;
772
773 case glslang::EbvSubgroupGeMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupGeMask;
777
778 case glslang::EbvSubgroupGtMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGtMask;
782
783 case glslang::EbvSubgroupLeMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupLeMask;
787
788 case glslang::EbvSubgroupLtMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800792#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800793 case glslang::EbvBaryCoordNoPersp:
794 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
795 return spv::BuiltInBaryCoordNoPerspAMD;
796
797 case glslang::EbvBaryCoordNoPerspCentroid:
798 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
799 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
800
801 case glslang::EbvBaryCoordNoPerspSample:
802 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
803 return spv::BuiltInBaryCoordNoPerspSampleAMD;
804
805 case glslang::EbvBaryCoordSmooth:
806 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
807 return spv::BuiltInBaryCoordSmoothAMD;
808
809 case glslang::EbvBaryCoordSmoothCentroid:
810 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
811 return spv::BuiltInBaryCoordSmoothCentroidAMD;
812
813 case glslang::EbvBaryCoordSmoothSample:
814 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
815 return spv::BuiltInBaryCoordSmoothSampleAMD;
816
817 case glslang::EbvBaryCoordPullModel:
818 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
819 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800820#endif
chaoc771d89f2017-01-13 01:10:53 -0800821
John Kessenich6c8aaac2017-02-27 01:20:51 -0700822 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700823 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700824 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700825 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826
827 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
chaoc771d89f2017-01-13 01:10:53 -0800832#ifdef NV_EXTENSIONS
833 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800834 if (!memberDeclaration) {
835 builder.addExtension(spv::E_SPV_NV_viewport_array2);
836 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
837 }
chaoc771d89f2017-01-13 01:10:53 -0800838 return spv::BuiltInViewportMaskNV;
839 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800840 if (!memberDeclaration) {
841 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
842 builder.addCapability(spv::CapabilityShaderStereoViewNV);
843 }
chaoc771d89f2017-01-13 01:10:53 -0800844 return spv::BuiltInSecondaryPositionNV;
845 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800846 if (!memberDeclaration) {
847 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
848 builder.addCapability(spv::CapabilityShaderStereoViewNV);
849 }
chaoc771d89f2017-01-13 01:10:53 -0800850 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800851 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800852 if (!memberDeclaration) {
853 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
854 builder.addCapability(spv::CapabilityPerViewAttributesNV);
855 }
chaocdf3956c2017-02-14 14:52:34 -0800856 return spv::BuiltInPositionPerViewNV;
857 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800858 if (!memberDeclaration) {
859 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
860 builder.addCapability(spv::CapabilityPerViewAttributesNV);
861 }
chaocdf3956c2017-02-14 14:52:34 -0800862 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700863 case glslang::EbvFragFullyCoveredNV:
864 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
865 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
866 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700867 case glslang::EbvFragmentSizeNV:
868 builder.addExtension(spv::E_SPV_NV_shading_rate);
869 builder.addCapability(spv::CapabilityShadingRateNV);
870 return spv::BuiltInFragmentSizeNV;
871 case glslang::EbvInvocationsPerPixelNV:
872 builder.addExtension(spv::E_SPV_NV_shading_rate);
873 builder.addCapability(spv::CapabilityShadingRateNV);
874 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700875
876 // raytracing
877 case glslang::EbvLaunchIdNV:
878 return spv::BuiltInLaunchIdNVX;
879 case glslang::EbvLaunchSizeNV:
880 return spv::BuiltInLaunchSizeNVX;
881 case glslang::EbvWorldRayOriginNV:
882 return spv::BuiltInWorldRayOriginNVX;
883 case glslang::EbvWorldRayDirectionNV:
884 return spv::BuiltInWorldRayDirectionNVX;
885 case glslang::EbvObjectRayOriginNV:
886 return spv::BuiltInObjectRayOriginNVX;
887 case glslang::EbvObjectRayDirectionNV:
888 return spv::BuiltInObjectRayDirectionNVX;
889 case glslang::EbvRayTminNV:
890 return spv::BuiltInRayTminNVX;
891 case glslang::EbvRayTmaxNV:
892 return spv::BuiltInRayTmaxNVX;
893 case glslang::EbvInstanceCustomIndexNV:
894 return spv::BuiltInInstanceCustomIndexNVX;
895 case glslang::EbvHitTNV:
896 return spv::BuiltInHitTNVX;
897 case glslang::EbvHitKindNV:
898 return spv::BuiltInHitKindNVX;
899 case glslang::EbvObjectToWorldNV:
900 return spv::BuiltInObjectToWorldNVX;
901 case glslang::EbvWorldToObjectNV:
902 return spv::BuiltInWorldToObjectNVX;
Chao Chen9eada4b2018-09-19 11:39:56 -0700903 case glslang::EbvBaryCoordNV:
904 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
905 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
906 return spv::BuiltInBaryCoordNV;
907 case glslang::EbvBaryCoordNoPerspNV:
908 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
909 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
910 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700911 case glslang::EbvTaskCountNV:
912 return spv::BuiltInTaskCountNV;
913 case glslang::EbvPrimitiveCountNV:
914 return spv::BuiltInPrimitiveCountNV;
915 case glslang::EbvPrimitiveIndicesNV:
916 return spv::BuiltInPrimitiveIndicesNV;
917 case glslang::EbvClipDistancePerViewNV:
918 return spv::BuiltInClipDistancePerViewNV;
919 case glslang::EbvCullDistancePerViewNV:
920 return spv::BuiltInCullDistancePerViewNV;
921 case glslang::EbvLayerPerViewNV:
922 return spv::BuiltInLayerPerViewNV;
923 case glslang::EbvMeshViewCountNV:
924 return spv::BuiltInMeshViewCountNV;
925 case glslang::EbvMeshViewIndicesNV:
926 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800927#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800928 default:
929 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600930 }
931}
932
Rex Xufc618912015-09-09 16:42:49 +0800933// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700934spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800935{
936 assert(type.getBasicType() == glslang::EbtSampler);
937
John Kessenich5d0fa972016-02-15 11:57:00 -0700938 // Check for capabilities
939 switch (type.getQualifier().layoutFormat) {
940 case glslang::ElfRg32f:
941 case glslang::ElfRg16f:
942 case glslang::ElfR11fG11fB10f:
943 case glslang::ElfR16f:
944 case glslang::ElfRgba16:
945 case glslang::ElfRgb10A2:
946 case glslang::ElfRg16:
947 case glslang::ElfRg8:
948 case glslang::ElfR16:
949 case glslang::ElfR8:
950 case glslang::ElfRgba16Snorm:
951 case glslang::ElfRg16Snorm:
952 case glslang::ElfRg8Snorm:
953 case glslang::ElfR16Snorm:
954 case glslang::ElfR8Snorm:
955
956 case glslang::ElfRg32i:
957 case glslang::ElfRg16i:
958 case glslang::ElfRg8i:
959 case glslang::ElfR16i:
960 case glslang::ElfR8i:
961
962 case glslang::ElfRgb10a2ui:
963 case glslang::ElfRg32ui:
964 case glslang::ElfRg16ui:
965 case glslang::ElfRg8ui:
966 case glslang::ElfR16ui:
967 case glslang::ElfR8ui:
968 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
969 break;
970
971 default:
972 break;
973 }
974
975 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800976 switch (type.getQualifier().layoutFormat) {
977 case glslang::ElfNone: return spv::ImageFormatUnknown;
978 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
979 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
980 case glslang::ElfR32f: return spv::ImageFormatR32f;
981 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
982 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
983 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
984 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
985 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
986 case glslang::ElfR16f: return spv::ImageFormatR16f;
987 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
988 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
989 case glslang::ElfRg16: return spv::ImageFormatRg16;
990 case glslang::ElfRg8: return spv::ImageFormatRg8;
991 case glslang::ElfR16: return spv::ImageFormatR16;
992 case glslang::ElfR8: return spv::ImageFormatR8;
993 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
994 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
995 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
996 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
997 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
998 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
999 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1000 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1001 case glslang::ElfR32i: return spv::ImageFormatR32i;
1002 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1003 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1004 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1005 case glslang::ElfR16i: return spv::ImageFormatR16i;
1006 case glslang::ElfR8i: return spv::ImageFormatR8i;
1007 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1008 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1009 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1010 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1011 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1012 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1013 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1014 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1015 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1016 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001017 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001018 }
1019}
1020
John Kesseniche18fd202018-01-30 11:01:39 -07001021spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001022{
John Kesseniche18fd202018-01-30 11:01:39 -07001023 if (selectionNode.getFlatten())
1024 return spv::SelectionControlFlattenMask;
1025 if (selectionNode.getDontFlatten())
1026 return spv::SelectionControlDontFlattenMask;
1027 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001028}
1029
John Kesseniche18fd202018-01-30 11:01:39 -07001030spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001031{
John Kesseniche18fd202018-01-30 11:01:39 -07001032 if (switchNode.getFlatten())
1033 return spv::SelectionControlFlattenMask;
1034 if (switchNode.getDontFlatten())
1035 return spv::SelectionControlDontFlattenMask;
1036 return spv::SelectionControlMaskNone;
1037}
1038
John Kessenicha2858d92018-01-31 08:11:18 -07001039// return a non-0 dependency if the dependency argument must be set
1040spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1041 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001042{
1043 spv::LoopControlMask control = spv::LoopControlMaskNone;
1044
1045 if (loopNode.getDontUnroll())
1046 control = control | spv::LoopControlDontUnrollMask;
1047 if (loopNode.getUnroll())
1048 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001049 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001050 control = control | spv::LoopControlDependencyInfiniteMask;
1051 else if (loopNode.getLoopDependency() > 0) {
1052 control = control | spv::LoopControlDependencyLengthMask;
1053 dependencyLength = loopNode.getLoopDependency();
1054 }
John Kesseniche18fd202018-01-30 11:01:39 -07001055
1056 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001057}
1058
John Kessenicha5c5fb62017-05-05 05:09:58 -06001059// Translate glslang type to SPIR-V storage class.
1060spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1061{
1062 if (type.getQualifier().isPipeInput())
1063 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001064 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001065 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001066
1067 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1068 type.getQualifier().storage == glslang::EvqUniform) {
1069 if (type.getBasicType() == glslang::EbtAtomicUint)
1070 return spv::StorageClassAtomicCounter;
1071 if (type.containsOpaque())
1072 return spv::StorageClassUniformConstant;
1073 }
1074
1075 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001076 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001077 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001078 }
1079
1080 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001081 if (type.getQualifier().layoutPushConstant)
1082 return spv::StorageClassPushConstant;
Chao Chenb50c02e2018-09-19 11:42:24 -07001083#ifdef NV_EXTENSIONS
1084 if (type.getQualifier().layoutShaderRecordNV)
1085 return spv::StorageClassShaderRecordBufferNVX;
1086#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001087 if (type.getBasicType() == glslang::EbtBlock)
1088 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001089 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001090 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001091
1092 switch (type.getQualifier().storage) {
1093 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1094 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1095 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1096 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001097#ifdef NV_EXTENSIONS
1098 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNVX;
1099 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNVX;
1100 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNVX;
1101#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001102 default:
1103 assert(0);
1104 break;
1105 }
1106
1107 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001108}
1109
John Kessenich5611c6d2018-04-05 11:25:02 -06001110// Add capabilities pertaining to how an array is indexed.
1111void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1112 const glslang::TType& indexType)
1113{
1114 if (indexType.getQualifier().isNonUniform()) {
1115 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001116 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001117 if (baseType.getBasicType() == glslang::EbtSampler) {
1118 if (baseType.getQualifier().hasAttachment())
1119 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1120 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1121 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1122 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1123 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1124 else if (baseType.isImage())
1125 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1126 else if (baseType.isTexture())
1127 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1128 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1129 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1130 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1131 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1132 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1133 }
1134 } else {
1135 // assume a dynamically uniform index
1136 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001137 if (baseType.getQualifier().hasAttachment()) {
1138 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001139 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001140 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1141 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001142 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001143 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1144 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001145 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001146 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001147 }
1148 }
1149}
1150
qining25262b32016-05-06 17:25:16 -04001151// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001152// descriptor set.
1153bool IsDescriptorResource(const glslang::TType& type)
1154{
John Kessenichf7497e22016-03-08 21:36:22 -07001155 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001156 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001157 return type.getQualifier().isUniformOrBuffer() &&
1158#ifdef NV_EXTENSIONS
1159 ! type.getQualifier().layoutShaderRecordNV &&
1160#endif
1161 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001162
1163 // non block...
1164 // basically samplerXXX/subpass/sampler/texture are all included
1165 // if they are the global-scope-class, not the function parameter
1166 // (or local, if they ever exist) class.
1167 if (type.getBasicType() == glslang::EbtSampler)
1168 return type.getQualifier().isUniformOrBuffer();
1169
1170 // None of the above.
1171 return false;
1172}
1173
John Kesseniche0b6cad2015-12-24 10:30:13 -07001174void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1175{
1176 if (child.layoutMatrix == glslang::ElmNone)
1177 child.layoutMatrix = parent.layoutMatrix;
1178
1179 if (parent.invariant)
1180 child.invariant = true;
1181 if (parent.nopersp)
1182 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001183#ifdef AMD_EXTENSIONS
1184 if (parent.explicitInterp)
1185 child.explicitInterp = true;
1186#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001187 if (parent.flat)
1188 child.flat = true;
1189 if (parent.centroid)
1190 child.centroid = true;
1191 if (parent.patch)
1192 child.patch = true;
1193 if (parent.sample)
1194 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001195 if (parent.coherent)
1196 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001197 if (parent.devicecoherent)
1198 child.devicecoherent = true;
1199 if (parent.queuefamilycoherent)
1200 child.queuefamilycoherent = true;
1201 if (parent.workgroupcoherent)
1202 child.workgroupcoherent = true;
1203 if (parent.subgroupcoherent)
1204 child.subgroupcoherent = true;
1205 if (parent.nonprivate)
1206 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001207 if (parent.volatil)
1208 child.volatil = true;
1209 if (parent.restrict)
1210 child.restrict = true;
1211 if (parent.readonly)
1212 child.readonly = true;
1213 if (parent.writeonly)
1214 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001215#ifdef NV_EXTENSIONS
1216 if (parent.perPrimitiveNV)
1217 child.perPrimitiveNV = true;
1218 if (parent.perViewNV)
1219 child.perViewNV = true;
1220 if (parent.perTaskNV)
1221 child.perTaskNV = true;
1222#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001223}
1224
John Kessenichf2b7f332016-09-01 17:05:23 -06001225bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001226{
John Kessenich7b9fa252016-01-21 18:56:57 -07001227 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001228 // - struct members might inherit from a struct declaration
1229 // (note that non-block structs don't explicitly inherit,
1230 // only implicitly, meaning no decoration involved)
1231 // - affect decorations on the struct members
1232 // (note smooth does not, and expecting something like volatile
1233 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001234 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001235 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001236}
1237
John Kessenich140f3df2015-06-26 16:58:36 -06001238//
1239// Implement the TGlslangToSpvTraverser class.
1240//
1241
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001242TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001243 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1244 : TIntermTraverser(true, false, true),
1245 options(options),
1246 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001247 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001248 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001249 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001250 glslangIntermediate(glslangIntermediate)
1251{
1252 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1253
1254 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001255 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1256 glslangIntermediate->getVersion());
1257
John Kessenich121853f2017-05-31 17:11:16 -06001258 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001259 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001260 builder.setSourceFile(glslangIntermediate->getSourceFile());
1261
1262 // Set the source shader's text. If for SPV version 1.0, include
1263 // a preamble in comments stating the OpModuleProcessed instructions.
1264 // Otherwise, emit those as actual instructions.
1265 std::string text;
1266 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1267 for (int p = 0; p < (int)processes.size(); ++p) {
1268 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1269 text.append("// OpModuleProcessed ");
1270 text.append(processes[p]);
1271 text.append("\n");
1272 } else
1273 builder.addModuleProcessed(processes[p]);
1274 }
1275 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1276 text.append("#line 1\n");
1277 text.append(glslangIntermediate->getSourceText());
1278 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001279 }
John Kessenich140f3df2015-06-26 16:58:36 -06001280 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001281 if (glslangIntermediate->usingVulkanMemoryModel()) {
1282 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1283 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1284 } else {
1285 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1286 }
John Kessenicheee9d532016-09-19 18:09:30 -06001287 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1288 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001289
1290 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001291 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1292 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001293 builder.addSourceExtension(it->c_str());
1294
1295 // Add the top-level modes for this shader.
1296
John Kessenich92187592016-02-01 13:45:25 -07001297 if (glslangIntermediate->getXfbMode()) {
1298 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001299 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001300 }
John Kessenich140f3df2015-06-26 16:58:36 -06001301
1302 unsigned int mode;
1303 switch (glslangIntermediate->getStage()) {
1304 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001305 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001306 break;
1307
steve-lunarge7412492017-03-23 11:56:07 -06001308 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001309 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001310 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001311
steve-lunarge7412492017-03-23 11:56:07 -06001312 glslang::TLayoutGeometry primitive;
1313
1314 if (glslangIntermediate->getStage() == EShLangTessControl) {
1315 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1316 primitive = glslangIntermediate->getOutputPrimitive();
1317 } else {
1318 primitive = glslangIntermediate->getInputPrimitive();
1319 }
1320
1321 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001322 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1323 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1324 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001325 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001326 }
John Kessenich4016e382016-07-15 11:53:56 -06001327 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001328 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1329
John Kesseniche6903322015-10-13 16:29:02 -06001330 switch (glslangIntermediate->getVertexSpacing()) {
1331 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1332 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1333 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001334 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001335 }
John Kessenich4016e382016-07-15 11:53:56 -06001336 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001337 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1338
1339 switch (glslangIntermediate->getVertexOrder()) {
1340 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1341 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001342 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001343 }
John Kessenich4016e382016-07-15 11:53:56 -06001344 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001345 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1346
1347 if (glslangIntermediate->getPointMode())
1348 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001349 break;
1350
1351 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001352 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001353 switch (glslangIntermediate->getInputPrimitive()) {
1354 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1355 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1356 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001357 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001358 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001359 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001360 }
John Kessenich4016e382016-07-15 11:53:56 -06001361 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001362 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001363
John Kessenich140f3df2015-06-26 16:58:36 -06001364 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1365
1366 switch (glslangIntermediate->getOutputPrimitive()) {
1367 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1368 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1369 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001370 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001371 }
John Kessenich4016e382016-07-15 11:53:56 -06001372 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001373 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1374 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1375 break;
1376
1377 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001378 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001379 if (glslangIntermediate->getPixelCenterInteger())
1380 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001381
John Kessenich140f3df2015-06-26 16:58:36 -06001382 if (glslangIntermediate->getOriginUpperLeft())
1383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001384 else
1385 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001386
1387 if (glslangIntermediate->getEarlyFragmentTests())
1388 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1389
chaocc1204522017-06-30 17:14:30 -07001390 if (glslangIntermediate->getPostDepthCoverage()) {
1391 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1392 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1393 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1394 }
1395
John Kesseniche6903322015-10-13 16:29:02 -06001396 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001397 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1398 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001399 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001400 }
John Kessenich4016e382016-07-15 11:53:56 -06001401 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001402 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1403
1404 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1405 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001406 break;
1407
1408 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001409 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001410 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1411 glslangIntermediate->getLocalSize(1),
1412 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001413#ifdef NV_EXTENSIONS
1414 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1415 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1416 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1417 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1418 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1419 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1421 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1422 }
1423#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001424 break;
1425
Chao Chen3c366992018-09-19 11:41:59 -07001426#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001427 case EShLangRayGenNV:
1428 case EShLangIntersectNV:
1429 case EShLangAnyHitNV:
1430 case EShLangClosestHitNV:
1431 case EShLangMissNV:
1432 case EShLangCallableNV:
1433 builder.addCapability(spv::CapabilityRaytracingNVX);
1434 builder.addExtension("SPV_NVX_raytracing");
1435 break;
Chao Chen3c366992018-09-19 11:41:59 -07001436 case EShLangTaskNV:
1437 case EShLangMeshNV:
1438 builder.addCapability(spv::CapabilityMeshShadingNV);
1439 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1441 glslangIntermediate->getLocalSize(1),
1442 glslangIntermediate->getLocalSize(2));
1443 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1446
1447 switch (glslangIntermediate->getOutputPrimitive()) {
1448 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1449 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1450 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1451 default: mode = spv::ExecutionModeMax; break;
1452 }
1453 if (mode != spv::ExecutionModeMax)
1454 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1455 }
1456 break;
1457#endif
1458
John Kessenich140f3df2015-06-26 16:58:36 -06001459 default:
1460 break;
1461 }
John Kessenich140f3df2015-06-26 16:58:36 -06001462}
1463
John Kessenichfca82622016-11-26 13:23:20 -07001464// Finish creating SPV, after the traversal is complete.
1465void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001466{
John Kessenichf04c51b2018-08-03 15:56:12 -06001467 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001468 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001469 builder.setBuildPoint(shaderEntry->getLastBlock());
1470 builder.leaveFunction();
1471 }
1472
John Kessenich7ba63412015-12-20 17:37:07 -07001473 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001474 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1475 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001476
John Kessenichf04c51b2018-08-03 15:56:12 -06001477 // Add capabilities, extensions, remove unneeded decorations, etc.,
1478 // based on the resulting SPIR-V.
1479 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001480}
1481
John Kessenichfca82622016-11-26 13:23:20 -07001482// Write the SPV into 'out'.
1483void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001484{
John Kessenichfca82622016-11-26 13:23:20 -07001485 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001486}
1487
1488//
1489// Implement the traversal functions.
1490//
1491// Return true from interior nodes to have the external traversal
1492// continue on to children. Return false if children were
1493// already processed.
1494//
1495
1496//
qining25262b32016-05-06 17:25:16 -04001497// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001498// - uniform/input reads
1499// - output writes
1500// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1501// - something simple that degenerates into the last bullet
1502//
1503void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1504{
qining75d1d802016-04-06 14:42:01 -04001505 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1506 if (symbol->getType().getQualifier().isSpecConstant())
1507 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1508
John Kessenich140f3df2015-06-26 16:58:36 -06001509 // getSymbolId() will set up all the IO decorations on the first call.
1510 // Formal function parameters were mapped during makeFunctions().
1511 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001512
1513 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1514 if (builder.isPointer(id)) {
1515 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001516 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1517 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1518 iOSet.insert(id);
1519 }
John Kessenich7ba63412015-12-20 17:37:07 -07001520 }
1521
1522 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001523 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001524 // Prepare to generate code for the access
1525
1526 // L-value chains will be computed left to right. We're on the symbol now,
1527 // which is the left-most part of the access chain, so now is "clear" time,
1528 // followed by setting the base.
1529 builder.clearAccessChain();
1530
1531 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001532 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001533 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001534 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001535 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001536 // These are also pure R-values.
1537 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001538 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001539 builder.setAccessChainRValue(id);
1540 else
1541 builder.setAccessChainLValue(id);
1542 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001543
1544 // Process linkage-only nodes for any special additional interface work.
1545 if (linkageOnly) {
1546 if (glslangIntermediate->getHlslFunctionality1()) {
1547 // Map implicit counter buffers to their originating buffers, which should have been
1548 // seen by now, given earlier pruning of unused counters, and preservation of order
1549 // of declaration.
1550 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1551 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1552 // Save possible originating buffers for counter buffers, keyed by
1553 // making the potential counter-buffer name.
1554 std::string keyName = symbol->getName().c_str();
1555 keyName = glslangIntermediate->addCounterBufferName(keyName);
1556 counterOriginator[keyName] = symbol;
1557 } else {
1558 // Handle a counter buffer, by finding the saved originating buffer.
1559 std::string keyName = symbol->getName().c_str();
1560 auto it = counterOriginator.find(keyName);
1561 if (it != counterOriginator.end()) {
1562 id = getSymbolId(it->second);
1563 if (id != spv::NoResult) {
1564 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001565 if (counterId != spv::NoResult) {
1566 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001567 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001568 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001569 }
1570 }
1571 }
1572 }
1573 }
1574 }
John Kessenich140f3df2015-06-26 16:58:36 -06001575}
1576
1577bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1578{
John Kesseniche485c7a2017-05-31 18:50:53 -06001579 builder.setLine(node->getLoc().line);
1580
qining40887662016-04-03 22:20:42 -04001581 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1582 if (node->getType().getQualifier().isSpecConstant())
1583 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1584
John Kessenich140f3df2015-06-26 16:58:36 -06001585 // First, handle special cases
1586 switch (node->getOp()) {
1587 case glslang::EOpAssign:
1588 case glslang::EOpAddAssign:
1589 case glslang::EOpSubAssign:
1590 case glslang::EOpMulAssign:
1591 case glslang::EOpVectorTimesMatrixAssign:
1592 case glslang::EOpVectorTimesScalarAssign:
1593 case glslang::EOpMatrixTimesScalarAssign:
1594 case glslang::EOpMatrixTimesMatrixAssign:
1595 case glslang::EOpDivAssign:
1596 case glslang::EOpModAssign:
1597 case glslang::EOpAndAssign:
1598 case glslang::EOpInclusiveOrAssign:
1599 case glslang::EOpExclusiveOrAssign:
1600 case glslang::EOpLeftShiftAssign:
1601 case glslang::EOpRightShiftAssign:
1602 // A bin-op assign "a += b" means the same thing as "a = a + b"
1603 // where a is evaluated before b. For a simple assignment, GLSL
1604 // says to evaluate the left before the right. So, always, left
1605 // node then right node.
1606 {
1607 // get the left l-value, save it away
1608 builder.clearAccessChain();
1609 node->getLeft()->traverse(this);
1610 spv::Builder::AccessChain lValue = builder.getAccessChain();
1611
1612 // evaluate the right
1613 builder.clearAccessChain();
1614 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001615 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001616
1617 if (node->getOp() != glslang::EOpAssign) {
1618 // the left is also an r-value
1619 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001620 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001623 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001624 TranslateNoContractionDecoration(node->getType().getQualifier()),
1625 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001626 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001627 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1628 node->getType().getBasicType());
1629
1630 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001631 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001632 }
1633
1634 // store the result
1635 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001636 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001637
1638 // assignments are expressions having an rValue after they are evaluated...
1639 builder.clearAccessChain();
1640 builder.setAccessChainRValue(rValue);
1641 }
1642 return false;
1643 case glslang::EOpIndexDirect:
1644 case glslang::EOpIndexDirectStruct:
1645 {
1646 // Get the left part of the access chain.
1647 node->getLeft()->traverse(this);
1648
1649 // Add the next element in the chain
1650
David Netoa901ffe2016-06-08 14:11:40 +01001651 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001652 if (! node->getLeft()->getType().isArray() &&
1653 node->getLeft()->getType().isVector() &&
1654 node->getOp() == glslang::EOpIndexDirect) {
1655 // This is essentially a hard-coded vector swizzle of size 1,
1656 // so short circuit the access-chain stuff with a swizzle.
1657 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001658 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001659 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001660 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001661 int spvIndex = glslangIndex;
1662 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1663 node->getOp() == glslang::EOpIndexDirectStruct)
1664 {
1665 // This may be, e.g., an anonymous block-member selection, which generally need
1666 // index remapping due to hidden members in anonymous blocks.
1667 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1668 assert(remapper.size() > 0);
1669 spvIndex = remapper[glslangIndex];
1670 }
John Kessenichebb50532016-05-16 19:22:05 -06001671
David Netoa901ffe2016-06-08 14:11:40 +01001672 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001673 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001674
1675 // Add capabilities here for accessing PointSize and clip/cull distance.
1676 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001677 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001678 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001679 }
1680 }
1681 return false;
1682 case glslang::EOpIndexIndirect:
1683 {
1684 // Structure or array or vector indirection.
1685 // Will use native SPIR-V access-chain for struct and array indirection;
1686 // matrices are arrays of vectors, so will also work for a matrix.
1687 // Will use the access chain's 'component' for variable index into a vector.
1688
1689 // This adapter is building access chains left to right.
1690 // Set up the access chain to the left.
1691 node->getLeft()->traverse(this);
1692
1693 // save it so that computing the right side doesn't trash it
1694 spv::Builder::AccessChain partial = builder.getAccessChain();
1695
1696 // compute the next index in the chain
1697 builder.clearAccessChain();
1698 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001699 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001700
John Kessenich5611c6d2018-04-05 11:25:02 -06001701 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1702
John Kessenich140f3df2015-06-26 16:58:36 -06001703 // restore the saved access chain
1704 builder.setAccessChain(partial);
1705
1706 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001707 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001708 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001709 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001710 }
1711 return false;
1712 case glslang::EOpVectorSwizzle:
1713 {
1714 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001715 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001716 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001717 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001718 }
1719 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001720 case glslang::EOpMatrixSwizzle:
1721 logger->missingFunctionality("matrix swizzle");
1722 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001723 case glslang::EOpLogicalOr:
1724 case glslang::EOpLogicalAnd:
1725 {
1726
1727 // These may require short circuiting, but can sometimes be done as straight
1728 // binary operations. The right operand must be short circuited if it has
1729 // side effects, and should probably be if it is complex.
1730 if (isTrivial(node->getRight()->getAsTyped()))
1731 break; // handle below as a normal binary operation
1732 // otherwise, we need to do dynamic short circuiting on the right operand
1733 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1734 builder.clearAccessChain();
1735 builder.setAccessChainRValue(result);
1736 }
1737 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001738 default:
1739 break;
1740 }
1741
1742 // Assume generic binary op...
1743
John Kessenich32cfd492016-02-02 12:37:46 -07001744 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001745 builder.clearAccessChain();
1746 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001747 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001748
John Kessenich32cfd492016-02-02 12:37:46 -07001749 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001750 builder.clearAccessChain();
1751 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001752 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001753
John Kessenich32cfd492016-02-02 12:37:46 -07001754 // get result
John Kessenichead86222018-03-28 18:01:20 -06001755 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001756 TranslateNoContractionDecoration(node->getType().getQualifier()),
1757 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001758 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001759 convertGlslangToSpvType(node->getType()), left, right,
1760 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001761
John Kessenich50e57562015-12-21 21:21:11 -07001762 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001763 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001764 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001765 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001766 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001767 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001768 return false;
1769 }
John Kessenich140f3df2015-06-26 16:58:36 -06001770}
1771
1772bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1773{
John Kesseniche485c7a2017-05-31 18:50:53 -06001774 builder.setLine(node->getLoc().line);
1775
qining40887662016-04-03 22:20:42 -04001776 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1777 if (node->getType().getQualifier().isSpecConstant())
1778 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1779
John Kessenichfc51d282015-08-19 13:34:18 -06001780 spv::Id result = spv::NoResult;
1781
1782 // try texturing first
1783 result = createImageTextureFunctionCall(node);
1784 if (result != spv::NoResult) {
1785 builder.clearAccessChain();
1786 builder.setAccessChainRValue(result);
1787
1788 return false; // done with this node
1789 }
1790
1791 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001792
1793 if (node->getOp() == glslang::EOpArrayLength) {
1794 // Quite special; won't want to evaluate the operand.
1795
John Kessenich5611c6d2018-04-05 11:25:02 -06001796 // Currently, the front-end does not allow .length() on an array until it is sized,
1797 // except for the last block membeor of an SSBO.
1798 // TODO: If this changes, link-time sized arrays might show up here, and need their
1799 // size extracted.
1800
John Kessenichc9a80832015-09-12 12:17:44 -06001801 // Normal .length() would have been constant folded by the front-end.
1802 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001803 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001804
John Kessenichc9a80832015-09-12 12:17:44 -06001805 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1806 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001807 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1808 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001809
1810 builder.clearAccessChain();
1811 builder.setAccessChainRValue(length);
1812
1813 return false;
1814 }
1815
John Kessenichfc51d282015-08-19 13:34:18 -06001816 // Start by evaluating the operand
1817
John Kessenich8c8505c2016-07-26 12:50:38 -06001818 // Does it need a swizzle inversion? If so, evaluation is inverted;
1819 // operate first on the swizzle base, then apply the swizzle.
1820 spv::Id invertedType = spv::NoType;
1821 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1822 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1823 invertedType = getInvertedSwizzleType(*node->getOperand());
1824
John Kessenich140f3df2015-06-26 16:58:36 -06001825 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001826 if (invertedType != spv::NoType)
1827 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1828 else
1829 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001830
Rex Xufc618912015-09-09 16:42:49 +08001831 spv::Id operand = spv::NoResult;
1832
1833 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1834 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001835 node->getOp() == glslang::EOpAtomicCounter ||
1836 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001837 operand = builder.accessChainGetLValue(); // Special case l-value operands
1838 else
John Kessenich32cfd492016-02-02 12:37:46 -07001839 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
John Kessenichead86222018-03-28 18:01:20 -06001841 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001842 TranslateNoContractionDecoration(node->getType().getQualifier()),
1843 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001846 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001847 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
1849 // if not, then possibly an operation
1850 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001851 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001852
1853 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001854 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001855 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001856 builder.addDecoration(result, decorations.nonUniform);
1857 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001858
John Kessenich140f3df2015-06-26 16:58:36 -06001859 builder.clearAccessChain();
1860 builder.setAccessChainRValue(result);
1861
1862 return false; // done with this node
1863 }
1864
1865 // it must be a special case, check...
1866 switch (node->getOp()) {
1867 case glslang::EOpPostIncrement:
1868 case glslang::EOpPostDecrement:
1869 case glslang::EOpPreIncrement:
1870 case glslang::EOpPreDecrement:
1871 {
1872 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001873 spv::Id one = 0;
1874 if (node->getBasicType() == glslang::EbtFloat)
1875 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001876 else if (node->getBasicType() == glslang::EbtDouble)
1877 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001878 else if (node->getBasicType() == glslang::EbtFloat16)
1879 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001880 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1881 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001882 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1883 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001884 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1885 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001886 else
1887 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001888 glslang::TOperator op;
1889 if (node->getOp() == glslang::EOpPreIncrement ||
1890 node->getOp() == glslang::EOpPostIncrement)
1891 op = glslang::EOpAdd;
1892 else
1893 op = glslang::EOpSub;
1894
John Kessenichead86222018-03-28 18:01:20 -06001895 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001896 convertGlslangToSpvType(node->getType()), operand, one,
1897 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001898 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001899
1900 // The result of operation is always stored, but conditionally the
1901 // consumed result. The consumed result is always an r-value.
1902 builder.accessChainStore(result);
1903 builder.clearAccessChain();
1904 if (node->getOp() == glslang::EOpPreIncrement ||
1905 node->getOp() == glslang::EOpPreDecrement)
1906 builder.setAccessChainRValue(result);
1907 else
1908 builder.setAccessChainRValue(operand);
1909 }
1910
1911 return false;
1912
1913 case glslang::EOpEmitStreamVertex:
1914 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1915 return false;
1916 case glslang::EOpEndStreamPrimitive:
1917 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1918 return false;
1919
1920 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001921 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001922 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001923 }
John Kessenich140f3df2015-06-26 16:58:36 -06001924}
1925
1926bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1927{
qining27e04a02016-04-14 16:40:20 -04001928 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1929 if (node->getType().getQualifier().isSpecConstant())
1930 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1931
John Kessenichfc51d282015-08-19 13:34:18 -06001932 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001933 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1934 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001935
1936 // try texturing
1937 result = createImageTextureFunctionCall(node);
1938 if (result != spv::NoResult) {
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(result);
1941
1942 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001943 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001944#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001945 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001946#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001947 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001948 // "imageStore" is a special case, which has no result
1949 return false;
1950 }
John Kessenichfc51d282015-08-19 13:34:18 -06001951
John Kessenich140f3df2015-06-26 16:58:36 -06001952 glslang::TOperator binOp = glslang::EOpNull;
1953 bool reduceComparison = true;
1954 bool isMatrix = false;
1955 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001956 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001957
1958 assert(node->getOp());
1959
John Kessenichf6640762016-08-01 19:44:00 -06001960 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001961
1962 switch (node->getOp()) {
1963 case glslang::EOpSequence:
1964 {
1965 if (preVisit)
1966 ++sequenceDepth;
1967 else
1968 --sequenceDepth;
1969
1970 if (sequenceDepth == 1) {
1971 // If this is the parent node of all the functions, we want to see them
1972 // early, so all call points have actual SPIR-V functions to reference.
1973 // In all cases, still let the traverser visit the children for us.
1974 makeFunctions(node->getAsAggregate()->getSequence());
1975
John Kessenich6fccb3c2016-09-19 16:01:41 -06001976 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001977 // anything else gets there, so visit out of order, doing them all now.
1978 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1979
John Kessenich6a60c2f2016-12-08 21:01:59 -07001980 // 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 -06001981 // so do them manually.
1982 visitFunctions(node->getAsAggregate()->getSequence());
1983
1984 return false;
1985 }
1986
1987 return true;
1988 }
1989 case glslang::EOpLinkerObjects:
1990 {
1991 if (visit == glslang::EvPreVisit)
1992 linkageOnly = true;
1993 else
1994 linkageOnly = false;
1995
1996 return true;
1997 }
1998 case glslang::EOpComma:
1999 {
2000 // processing from left to right naturally leaves the right-most
2001 // lying around in the access chain
2002 glslang::TIntermSequence& glslangOperands = node->getSequence();
2003 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2004 glslangOperands[i]->traverse(this);
2005
2006 return false;
2007 }
2008 case glslang::EOpFunction:
2009 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002010 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002011 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002012 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002013 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002014 } else {
2015 handleFunctionEntry(node);
2016 }
2017 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002018 if (inEntryPoint)
2019 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002020 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002021 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002022 }
2023
2024 return true;
2025 case glslang::EOpParameters:
2026 // Parameters will have been consumed by EOpFunction processing, but not
2027 // the body, so we still visited the function node's children, making this
2028 // child redundant.
2029 return false;
2030 case glslang::EOpFunctionCall:
2031 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002032 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002033 if (node->isUserDefined())
2034 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002035 // 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 -07002036 if (result) {
2037 builder.clearAccessChain();
2038 builder.setAccessChainRValue(result);
2039 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002040 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002041
2042 return false;
2043 }
2044 case glslang::EOpConstructMat2x2:
2045 case glslang::EOpConstructMat2x3:
2046 case glslang::EOpConstructMat2x4:
2047 case glslang::EOpConstructMat3x2:
2048 case glslang::EOpConstructMat3x3:
2049 case glslang::EOpConstructMat3x4:
2050 case glslang::EOpConstructMat4x2:
2051 case glslang::EOpConstructMat4x3:
2052 case glslang::EOpConstructMat4x4:
2053 case glslang::EOpConstructDMat2x2:
2054 case glslang::EOpConstructDMat2x3:
2055 case glslang::EOpConstructDMat2x4:
2056 case glslang::EOpConstructDMat3x2:
2057 case glslang::EOpConstructDMat3x3:
2058 case glslang::EOpConstructDMat3x4:
2059 case glslang::EOpConstructDMat4x2:
2060 case glslang::EOpConstructDMat4x3:
2061 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002062 case glslang::EOpConstructIMat2x2:
2063 case glslang::EOpConstructIMat2x3:
2064 case glslang::EOpConstructIMat2x4:
2065 case glslang::EOpConstructIMat3x2:
2066 case glslang::EOpConstructIMat3x3:
2067 case glslang::EOpConstructIMat3x4:
2068 case glslang::EOpConstructIMat4x2:
2069 case glslang::EOpConstructIMat4x3:
2070 case glslang::EOpConstructIMat4x4:
2071 case glslang::EOpConstructUMat2x2:
2072 case glslang::EOpConstructUMat2x3:
2073 case glslang::EOpConstructUMat2x4:
2074 case glslang::EOpConstructUMat3x2:
2075 case glslang::EOpConstructUMat3x3:
2076 case glslang::EOpConstructUMat3x4:
2077 case glslang::EOpConstructUMat4x2:
2078 case glslang::EOpConstructUMat4x3:
2079 case glslang::EOpConstructUMat4x4:
2080 case glslang::EOpConstructBMat2x2:
2081 case glslang::EOpConstructBMat2x3:
2082 case glslang::EOpConstructBMat2x4:
2083 case glslang::EOpConstructBMat3x2:
2084 case glslang::EOpConstructBMat3x3:
2085 case glslang::EOpConstructBMat3x4:
2086 case glslang::EOpConstructBMat4x2:
2087 case glslang::EOpConstructBMat4x3:
2088 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002089 case glslang::EOpConstructF16Mat2x2:
2090 case glslang::EOpConstructF16Mat2x3:
2091 case glslang::EOpConstructF16Mat2x4:
2092 case glslang::EOpConstructF16Mat3x2:
2093 case glslang::EOpConstructF16Mat3x3:
2094 case glslang::EOpConstructF16Mat3x4:
2095 case glslang::EOpConstructF16Mat4x2:
2096 case glslang::EOpConstructF16Mat4x3:
2097 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002098 isMatrix = true;
2099 // fall through
2100 case glslang::EOpConstructFloat:
2101 case glslang::EOpConstructVec2:
2102 case glslang::EOpConstructVec3:
2103 case glslang::EOpConstructVec4:
2104 case glslang::EOpConstructDouble:
2105 case glslang::EOpConstructDVec2:
2106 case glslang::EOpConstructDVec3:
2107 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002108 case glslang::EOpConstructFloat16:
2109 case glslang::EOpConstructF16Vec2:
2110 case glslang::EOpConstructF16Vec3:
2111 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002112 case glslang::EOpConstructBool:
2113 case glslang::EOpConstructBVec2:
2114 case glslang::EOpConstructBVec3:
2115 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002116 case glslang::EOpConstructInt8:
2117 case glslang::EOpConstructI8Vec2:
2118 case glslang::EOpConstructI8Vec3:
2119 case glslang::EOpConstructI8Vec4:
2120 case glslang::EOpConstructUint8:
2121 case glslang::EOpConstructU8Vec2:
2122 case glslang::EOpConstructU8Vec3:
2123 case glslang::EOpConstructU8Vec4:
2124 case glslang::EOpConstructInt16:
2125 case glslang::EOpConstructI16Vec2:
2126 case glslang::EOpConstructI16Vec3:
2127 case glslang::EOpConstructI16Vec4:
2128 case glslang::EOpConstructUint16:
2129 case glslang::EOpConstructU16Vec2:
2130 case glslang::EOpConstructU16Vec3:
2131 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002132 case glslang::EOpConstructInt:
2133 case glslang::EOpConstructIVec2:
2134 case glslang::EOpConstructIVec3:
2135 case glslang::EOpConstructIVec4:
2136 case glslang::EOpConstructUint:
2137 case glslang::EOpConstructUVec2:
2138 case glslang::EOpConstructUVec3:
2139 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002140 case glslang::EOpConstructInt64:
2141 case glslang::EOpConstructI64Vec2:
2142 case glslang::EOpConstructI64Vec3:
2143 case glslang::EOpConstructI64Vec4:
2144 case glslang::EOpConstructUint64:
2145 case glslang::EOpConstructU64Vec2:
2146 case glslang::EOpConstructU64Vec3:
2147 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002148 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002149 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002151 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002152 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002153 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002154 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002155 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002156 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002157 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002158 std::vector<spv::Id> constituents;
2159 for (int c = 0; c < (int)arguments.size(); ++c)
2160 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002161 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002162 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002163 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002164 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002165 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002166
2167 builder.clearAccessChain();
2168 builder.setAccessChainRValue(constructed);
2169
2170 return false;
2171 }
2172
2173 // These six are component-wise compares with component-wise results.
2174 // Forward on to createBinaryOperation(), requesting a vector result.
2175 case glslang::EOpLessThan:
2176 case glslang::EOpGreaterThan:
2177 case glslang::EOpLessThanEqual:
2178 case glslang::EOpGreaterThanEqual:
2179 case glslang::EOpVectorEqual:
2180 case glslang::EOpVectorNotEqual:
2181 {
2182 // Map the operation to a binary
2183 binOp = node->getOp();
2184 reduceComparison = false;
2185 switch (node->getOp()) {
2186 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2187 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2188 default: binOp = node->getOp(); break;
2189 }
2190
2191 break;
2192 }
2193 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002194 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002195 binOp = glslang::EOpMul;
2196 break;
2197 case glslang::EOpOuterProduct:
2198 // two vectors multiplied to make a matrix
2199 binOp = glslang::EOpOuterProduct;
2200 break;
2201 case glslang::EOpDot:
2202 {
qining25262b32016-05-06 17:25:16 -04002203 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002204 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002205 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002206 binOp = glslang::EOpMul;
2207 break;
2208 }
2209 case glslang::EOpMod:
2210 // when an aggregate, this is the floating-point mod built-in function,
2211 // which can be emitted by the one in createBinaryOperation()
2212 binOp = glslang::EOpMod;
2213 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002214 case glslang::EOpEmitVertex:
2215 case glslang::EOpEndPrimitive:
2216 case glslang::EOpBarrier:
2217 case glslang::EOpMemoryBarrier:
2218 case glslang::EOpMemoryBarrierAtomicCounter:
2219 case glslang::EOpMemoryBarrierBuffer:
2220 case glslang::EOpMemoryBarrierImage:
2221 case glslang::EOpMemoryBarrierShared:
2222 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002223 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002224 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002225 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002226 case glslang::EOpWorkgroupMemoryBarrier:
2227 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002228 case glslang::EOpSubgroupBarrier:
2229 case glslang::EOpSubgroupMemoryBarrier:
2230 case glslang::EOpSubgroupMemoryBarrierBuffer:
2231 case glslang::EOpSubgroupMemoryBarrierImage:
2232 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002233 noReturnValue = true;
2234 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2235 break;
2236
Jeff Bolz36831c92018-09-05 10:11:41 -05002237 case glslang::EOpAtomicStore:
2238 noReturnValue = true;
2239 // fallthrough
2240 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002241 case glslang::EOpAtomicAdd:
2242 case glslang::EOpAtomicMin:
2243 case glslang::EOpAtomicMax:
2244 case glslang::EOpAtomicAnd:
2245 case glslang::EOpAtomicOr:
2246 case glslang::EOpAtomicXor:
2247 case glslang::EOpAtomicExchange:
2248 case glslang::EOpAtomicCompSwap:
2249 atomic = true;
2250 break;
2251
John Kessenich0d0c6d32017-07-23 16:08:26 -06002252 case glslang::EOpAtomicCounterAdd:
2253 case glslang::EOpAtomicCounterSubtract:
2254 case glslang::EOpAtomicCounterMin:
2255 case glslang::EOpAtomicCounterMax:
2256 case glslang::EOpAtomicCounterAnd:
2257 case glslang::EOpAtomicCounterOr:
2258 case glslang::EOpAtomicCounterXor:
2259 case glslang::EOpAtomicCounterExchange:
2260 case glslang::EOpAtomicCounterCompSwap:
2261 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2262 builder.addCapability(spv::CapabilityAtomicStorageOps);
2263 atomic = true;
2264 break;
2265
Chao Chen3c366992018-09-19 11:41:59 -07002266#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002267 case glslang::EOpIgnoreIntersectionNV:
2268 case glslang::EOpTerminateRayNV:
2269 case glslang::EOpTraceNV:
Chao Chen3c366992018-09-19 11:41:59 -07002270 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2271 noReturnValue = true;
2272 break;
2273#endif
2274
John Kessenich140f3df2015-06-26 16:58:36 -06002275 default:
2276 break;
2277 }
2278
2279 //
2280 // See if it maps to a regular operation.
2281 //
John Kessenich140f3df2015-06-26 16:58:36 -06002282 if (binOp != glslang::EOpNull) {
2283 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2284 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2285 assert(left && right);
2286
2287 builder.clearAccessChain();
2288 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002289 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002290
2291 builder.clearAccessChain();
2292 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002293 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
John Kesseniche485c7a2017-05-31 18:50:53 -06002295 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002296 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002297 TranslateNoContractionDecoration(node->getType().getQualifier()),
2298 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002299 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002300 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002301 left->getType().getBasicType(), reduceComparison);
2302
2303 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002304 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002305 builder.clearAccessChain();
2306 builder.setAccessChainRValue(result);
2307
2308 return false;
2309 }
2310
John Kessenich426394d2015-07-23 10:22:48 -06002311 //
2312 // Create the list of operands.
2313 //
John Kessenich140f3df2015-06-26 16:58:36 -06002314 glslang::TIntermSequence& glslangOperands = node->getSequence();
2315 std::vector<spv::Id> operands;
2316 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002317 // special case l-value operands; there are just a few
2318 bool lvalue = false;
2319 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002320 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002321 case glslang::EOpModf:
2322 if (arg == 1)
2323 lvalue = true;
2324 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002325 case glslang::EOpInterpolateAtSample:
2326 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002327#ifdef AMD_EXTENSIONS
2328 case glslang::EOpInterpolateAtVertex:
2329#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002330 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002331 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002332
2333 // Does it need a swizzle inversion? If so, evaluation is inverted;
2334 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002335 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002336 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2337 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2338 }
Rex Xu7a26c172015-12-08 17:12:09 +08002339 break;
Rex Xud4782c12015-09-06 16:30:11 +08002340 case glslang::EOpAtomicAdd:
2341 case glslang::EOpAtomicMin:
2342 case glslang::EOpAtomicMax:
2343 case glslang::EOpAtomicAnd:
2344 case glslang::EOpAtomicOr:
2345 case glslang::EOpAtomicXor:
2346 case glslang::EOpAtomicExchange:
2347 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002348 case glslang::EOpAtomicLoad:
2349 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002350 case glslang::EOpAtomicCounterAdd:
2351 case glslang::EOpAtomicCounterSubtract:
2352 case glslang::EOpAtomicCounterMin:
2353 case glslang::EOpAtomicCounterMax:
2354 case glslang::EOpAtomicCounterAnd:
2355 case glslang::EOpAtomicCounterOr:
2356 case glslang::EOpAtomicCounterXor:
2357 case glslang::EOpAtomicCounterExchange:
2358 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002359 if (arg == 0)
2360 lvalue = true;
2361 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002362 case glslang::EOpAddCarry:
2363 case glslang::EOpSubBorrow:
2364 if (arg == 2)
2365 lvalue = true;
2366 break;
2367 case glslang::EOpUMulExtended:
2368 case glslang::EOpIMulExtended:
2369 if (arg >= 2)
2370 lvalue = true;
2371 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 default:
2373 break;
2374 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002375 builder.clearAccessChain();
2376 if (invertedType != spv::NoType && arg == 0)
2377 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2378 else
2379 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002380 if (lvalue)
2381 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002382 else {
2383 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002384 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002385 }
John Kessenich140f3df2015-06-26 16:58:36 -06002386 }
John Kessenich426394d2015-07-23 10:22:48 -06002387
John Kesseniche485c7a2017-05-31 18:50:53 -06002388 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002389 if (atomic) {
2390 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002391 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002392 } else {
2393 // Pass through to generic operations.
2394 switch (glslangOperands.size()) {
2395 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002396 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002397 break;
2398 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002399 {
2400 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002401 TranslateNoContractionDecoration(node->getType().getQualifier()),
2402 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002403 result = createUnaryOperation(
2404 node->getOp(), decorations,
2405 resultType(), operands.front(),
2406 glslangOperands[0]->getAsTyped()->getBasicType());
2407 }
John Kessenich426394d2015-07-23 10:22:48 -06002408 break;
2409 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002410 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002411 break;
2412 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002413 if (invertedType)
2414 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002415 }
2416
2417 if (noReturnValue)
2418 return false;
2419
2420 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002421 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002422 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002423 } else {
2424 builder.clearAccessChain();
2425 builder.setAccessChainRValue(result);
2426 return false;
2427 }
2428}
2429
John Kessenich433e9ff2017-01-26 20:31:11 -07002430// This path handles both if-then-else and ?:
2431// The if-then-else has a node type of void, while
2432// ?: has either a void or a non-void node type
2433//
2434// Leaving the result, when not void:
2435// GLSL only has r-values as the result of a :?, but
2436// if we have an l-value, that can be more efficient if it will
2437// become the base of a complex r-value expression, because the
2438// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002439bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2440{
John Kessenich4bee5312018-02-20 21:29:05 -07002441 // See if it simple and safe, or required, to execute both sides.
2442 // Crucially, side effects must be either semantically required or avoided,
2443 // and there are performance trade-offs.
2444 // Return true if required or a good idea (and safe) to execute both sides,
2445 // false otherwise.
2446 const auto bothSidesPolicy = [&]() -> bool {
2447 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002448 if (node->getTrueBlock() == nullptr ||
2449 node->getFalseBlock() == nullptr)
2450 return false;
2451
John Kessenich4bee5312018-02-20 21:29:05 -07002452 // required? (unless we write additional code to look for side effects
2453 // and make performance trade-offs if none are present)
2454 if (!node->getShortCircuit())
2455 return true;
2456
2457 // if not required to execute both, decide based on performance/practicality...
2458
2459 // see if OpSelect can handle it
2460 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2461 node->getBasicType() == glslang::EbtVoid)
2462 return false;
2463
John Kessenich433e9ff2017-01-26 20:31:11 -07002464 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2465 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2466
2467 // return true if a single operand to ? : is okay for OpSelect
2468 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002469 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002470 };
2471
2472 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2473 operandOkay(node->getFalseBlock()->getAsTyped());
2474 };
2475
John Kessenich4bee5312018-02-20 21:29:05 -07002476 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2477 // emit the condition before doing anything with selection
2478 node->getCondition()->traverse(this);
2479 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2480
2481 // Find a way of executing both sides and selecting the right result.
2482 const auto executeBothSides = [&]() -> void {
2483 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002484 node->getTrueBlock()->traverse(this);
2485 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2486 node->getFalseBlock()->traverse(this);
2487 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2488
John Kesseniche485c7a2017-05-31 18:50:53 -06002489 builder.setLine(node->getLoc().line);
2490
John Kessenich4bee5312018-02-20 21:29:05 -07002491 // done if void
2492 if (node->getBasicType() == glslang::EbtVoid)
2493 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002494
John Kessenich4bee5312018-02-20 21:29:05 -07002495 // emit code to select between trueValue and falseValue
2496
2497 // see if OpSelect can handle it
2498 if (node->getType().isScalar() || node->getType().isVector()) {
2499 // Emit OpSelect for this selection.
2500
2501 // smear condition to vector, if necessary (AST is always scalar)
2502 if (builder.isVector(trueValue))
2503 condition = builder.smearScalar(spv::NoPrecision, condition,
2504 builder.makeVectorType(builder.makeBoolType(),
2505 builder.getNumComponents(trueValue)));
2506
2507 // OpSelect
2508 result = builder.createTriOp(spv::OpSelect,
2509 convertGlslangToSpvType(node->getType()), condition,
2510 trueValue, falseValue);
2511
2512 builder.clearAccessChain();
2513 builder.setAccessChainRValue(result);
2514 } else {
2515 // We need control flow to select the result.
2516 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2517 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2518
2519 // Selection control:
2520 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2521
2522 // make an "if" based on the value created by the condition
2523 spv::Builder::If ifBuilder(condition, control, builder);
2524
2525 // emit the "then" statement
2526 builder.createStore(trueValue, result);
2527 ifBuilder.makeBeginElse();
2528 // emit the "else" statement
2529 builder.createStore(falseValue, result);
2530
2531 // finish off the control flow
2532 ifBuilder.makeEndIf();
2533
2534 builder.clearAccessChain();
2535 builder.setAccessChainLValue(result);
2536 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002537 };
2538
John Kessenich4bee5312018-02-20 21:29:05 -07002539 // Execute the one side needed, as per the condition
2540 const auto executeOneSide = [&]() {
2541 // Always emit control flow.
2542 if (node->getBasicType() != glslang::EbtVoid)
2543 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002544
John Kessenich4bee5312018-02-20 21:29:05 -07002545 // Selection control:
2546 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2547
2548 // make an "if" based on the value created by the condition
2549 spv::Builder::If ifBuilder(condition, control, builder);
2550
2551 // emit the "then" statement
2552 if (node->getTrueBlock() != nullptr) {
2553 node->getTrueBlock()->traverse(this);
2554 if (result != spv::NoResult)
2555 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2556 }
2557
2558 if (node->getFalseBlock() != nullptr) {
2559 ifBuilder.makeBeginElse();
2560 // emit the "else" statement
2561 node->getFalseBlock()->traverse(this);
2562 if (result != spv::NoResult)
2563 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2564 }
2565
2566 // finish off the control flow
2567 ifBuilder.makeEndIf();
2568
2569 if (result != spv::NoResult) {
2570 builder.clearAccessChain();
2571 builder.setAccessChainLValue(result);
2572 }
2573 };
2574
2575 // Try for OpSelect (or a requirement to execute both sides)
2576 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002577 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2578 if (node->getType().getQualifier().isSpecConstant())
2579 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002580 executeBothSides();
2581 } else
2582 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002583
2584 return false;
2585}
2586
2587bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2588{
2589 // emit and get the condition before doing anything with switch
2590 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002591 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002592
Rex Xu57e65922017-07-04 23:23:40 +08002593 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002594 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002595
John Kessenich140f3df2015-06-26 16:58:36 -06002596 // browse the children to sort out code segments
2597 int defaultSegment = -1;
2598 std::vector<TIntermNode*> codeSegments;
2599 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2600 std::vector<int> caseValues;
2601 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2602 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2603 TIntermNode* child = *c;
2604 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002605 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002606 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002607 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002608 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2609 } else
2610 codeSegments.push_back(child);
2611 }
2612
qining25262b32016-05-06 17:25:16 -04002613 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002614 // statements between the last case and the end of the switch statement
2615 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2616 (int)codeSegments.size() == defaultSegment)
2617 codeSegments.push_back(nullptr);
2618
2619 // make the switch statement
2620 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002621 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002622
2623 // emit all the code in the segments
2624 breakForLoop.push(false);
2625 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2626 builder.nextSwitchSegment(segmentBlocks, s);
2627 if (codeSegments[s])
2628 codeSegments[s]->traverse(this);
2629 else
2630 builder.addSwitchBreak();
2631 }
2632 breakForLoop.pop();
2633
2634 builder.endSwitch(segmentBlocks);
2635
2636 return false;
2637}
2638
2639void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2640{
2641 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002642 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002643
2644 builder.clearAccessChain();
2645 builder.setAccessChainRValue(constant);
2646}
2647
2648bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2649{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002650 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002651 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002652
2653 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002654 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2655 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002656
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002657 // Spec requires back edges to target header blocks, and every header block
2658 // must dominate its merge block. Make a header block first to ensure these
2659 // conditions are met. By definition, it will contain OpLoopMerge, followed
2660 // by a block-ending branch. But we don't want to put any other body/test
2661 // instructions in it, since the body/test may have arbitrary instructions,
2662 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002663 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002664 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002665 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002666 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002667 spv::Block& test = builder.makeNewBlock();
2668 builder.createBranch(&test);
2669
2670 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002671 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002672 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002673 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2674
2675 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002676 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002677 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002678 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002679 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002680 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002681
2682 builder.setBuildPoint(&blocks.continue_target);
2683 if (node->getTerminal())
2684 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002685 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002686 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002687 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002688 builder.createBranch(&blocks.body);
2689
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002690 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002691 builder.setBuildPoint(&blocks.body);
2692 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002693 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002694 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002695 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002696
2697 builder.setBuildPoint(&blocks.continue_target);
2698 if (node->getTerminal())
2699 node->getTerminal()->traverse(this);
2700 if (node->getTest()) {
2701 node->getTest()->traverse(this);
2702 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002703 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002704 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002705 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002706 // TODO: unless there was a break/return/discard instruction
2707 // somewhere in the body, this is an infinite loop, so we should
2708 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002709 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002710 }
John Kessenich140f3df2015-06-26 16:58:36 -06002711 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002712 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002713 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002714 return false;
2715}
2716
2717bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2718{
2719 if (node->getExpression())
2720 node->getExpression()->traverse(this);
2721
John Kesseniche485c7a2017-05-31 18:50:53 -06002722 builder.setLine(node->getLoc().line);
2723
John Kessenich140f3df2015-06-26 16:58:36 -06002724 switch (node->getFlowOp()) {
2725 case glslang::EOpKill:
2726 builder.makeDiscard();
2727 break;
2728 case glslang::EOpBreak:
2729 if (breakForLoop.top())
2730 builder.createLoopExit();
2731 else
2732 builder.addSwitchBreak();
2733 break;
2734 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002735 builder.createLoopContinue();
2736 break;
2737 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002738 if (node->getExpression()) {
2739 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2740 spv::Id returnId = accessChainLoad(glslangReturnType);
2741 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2742 builder.clearAccessChain();
2743 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2744 builder.setAccessChainLValue(copyId);
2745 multiTypeStore(glslangReturnType, returnId);
2746 returnId = builder.createLoad(copyId);
2747 }
2748 builder.makeReturn(false, returnId);
2749 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002750 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002751
2752 builder.clearAccessChain();
2753 break;
2754
2755 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002756 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002757 break;
2758 }
2759
2760 return false;
2761}
2762
2763spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2764{
qining25262b32016-05-06 17:25:16 -04002765 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002766 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002767 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002768 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002769 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002770 }
2771
2772 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002773 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002774 spv::Id spvType = convertGlslangToSpvType(node->getType());
2775
Rex Xucabbb782017-03-24 13:41:14 +08002776 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2777 node->getType().containsBasicType(glslang::EbtInt16) ||
2778 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002779 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002780 switch (storageClass) {
2781 case spv::StorageClassInput:
2782 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002783 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002784 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002785 break;
2786 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002787 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002788 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002789 break;
2790 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002791 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002792 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2793 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002794 else
2795 builder.addCapability(spv::CapabilityStorageUniform16);
2796 break;
2797 case spv::StorageClassStorageBuffer:
2798 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2799 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2800 break;
2801 default:
2802 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002803 }
2804 }
Rex Xuf89ad982017-04-07 23:22:33 +08002805
John Kessenich312dcfb2018-07-03 13:19:51 -06002806 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2807 node->getType().containsBasicType(glslang::EbtUint8);
2808 if (contains8BitType) {
2809 if (storageClass == spv::StorageClassPushConstant) {
2810 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2811 builder.addCapability(spv::CapabilityStoragePushConstant8);
2812 } else if (storageClass == spv::StorageClassUniform) {
2813 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2814 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2815 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2816 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2817 }
2818 }
2819
John Kessenich140f3df2015-06-26 16:58:36 -06002820 const char* name = node->getName().c_str();
2821 if (glslang::IsAnonymous(name))
2822 name = "";
2823
2824 return builder.createVariable(storageClass, spvType, name);
2825}
2826
2827// Return type Id of the sampled type.
2828spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2829{
2830 switch (sampler.type) {
2831 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002832#ifdef AMD_EXTENSIONS
2833 case glslang::EbtFloat16:
2834 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2835 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2836 return builder.makeFloatType(16);
2837#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002838 case glslang::EbtInt: return builder.makeIntType(32);
2839 case glslang::EbtUint: return builder.makeUintType(32);
2840 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002841 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002842 return builder.makeFloatType(32);
2843 }
2844}
2845
John Kessenich8c8505c2016-07-26 12:50:38 -06002846// If node is a swizzle operation, return the type that should be used if
2847// the swizzle base is first consumed by another operation, before the swizzle
2848// is applied.
2849spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2850{
John Kessenichecba76f2017-01-06 00:34:48 -07002851 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002852 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2853 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2854 else
2855 return spv::NoType;
2856}
2857
2858// When inverting a swizzle with a parent op, this function
2859// will apply the swizzle operation to a completed parent operation.
2860spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2861{
2862 std::vector<unsigned> swizzle;
2863 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2864 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2865}
2866
John Kessenich8c8505c2016-07-26 12:50:38 -06002867// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2868void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2869{
2870 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2871 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2872 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2873}
2874
John Kessenich3ac051e2015-12-20 11:29:16 -07002875// Convert from a glslang type to an SPV type, by calling into a
2876// recursive version of this function. This establishes the inherited
2877// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002878spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2879{
John Kessenichead86222018-03-28 18:01:20 -06002880 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002881}
2882
2883// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002884// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002885// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002886spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2887 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002888{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002889 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002890
2891 switch (type.getBasicType()) {
2892 case glslang::EbtVoid:
2893 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002894 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002895 break;
2896 case glslang::EbtFloat:
2897 spvType = builder.makeFloatType(32);
2898 break;
2899 case glslang::EbtDouble:
2900 spvType = builder.makeFloatType(64);
2901 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002902 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002903 spvType = builder.makeFloatType(16);
2904 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002905 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002906 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2907 // a 32-bit int where non-0 means true.
2908 if (explicitLayout != glslang::ElpNone)
2909 spvType = builder.makeUintType(32);
2910 else
2911 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002912 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002913 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002914 spvType = builder.makeIntType(8);
2915 break;
2916 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002917 spvType = builder.makeUintType(8);
2918 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002919 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002920 spvType = builder.makeIntType(16);
2921 break;
2922 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002923 spvType = builder.makeUintType(16);
2924 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 case glslang::EbtInt:
2926 spvType = builder.makeIntType(32);
2927 break;
2928 case glslang::EbtUint:
2929 spvType = builder.makeUintType(32);
2930 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002931 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002932 spvType = builder.makeIntType(64);
2933 break;
2934 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002935 spvType = builder.makeUintType(64);
2936 break;
John Kessenich426394d2015-07-23 10:22:48 -06002937 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002938 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002939 spvType = builder.makeUintType(32);
2940 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002941#ifdef NV_EXTENSIONS
2942 case glslang::EbtAccStructNV:
2943 spvType = builder.makeAccelerationStructureNVType();
2944 break;
2945#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002946 case glslang::EbtSampler:
2947 {
2948 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002949 if (sampler.sampler) {
2950 // pure sampler
2951 spvType = builder.makeSamplerType();
2952 } else {
2953 // an image is present, make its type
2954 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2955 sampler.image ? 2 : 1, TranslateImageFormat(type));
2956 if (sampler.combined) {
2957 // already has both image and sampler, make the combined type
2958 spvType = builder.makeSampledImageType(spvType);
2959 }
John Kessenich55e7d112015-11-15 21:33:39 -07002960 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002961 }
John Kessenich140f3df2015-06-26 16:58:36 -06002962 break;
2963 case glslang::EbtStruct:
2964 case glslang::EbtBlock:
2965 {
2966 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002967 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002968
2969 // Try to share structs for different layouts, but not yet for other
2970 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002971 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002972 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002973 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975
2976 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002977 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002978 memberRemapper[glslangMembers].resize(glslangMembers->size());
2979 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002980 }
2981 break;
2982 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002983 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985 }
2986
2987 if (type.isMatrix())
2988 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2989 else {
2990 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2991 if (type.getVectorSize() > 1)
2992 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2993 }
2994
2995 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002996 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2997
John Kessenichc9a80832015-09-12 12:17:44 -06002998 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002999 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003000 // We need to decorate array strides for types needing explicit layout, except blocks.
3001 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003002 // Use a dummy glslang type for querying internal strides of
3003 // arrays of arrays, but using just a one-dimensional array.
3004 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003005 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3006 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003007
3008 // Will compute the higher-order strides here, rather than making a whole
3009 // pile of types and doing repetitive recursion on their contents.
3010 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3011 }
John Kessenichf8842e52016-01-04 19:22:56 -07003012
3013 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003014 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003015 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003016 if (stride > 0)
3017 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003018 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003019 }
3020 } else {
3021 // single-dimensional array, and don't yet have stride
3022
John Kessenichf8842e52016-01-04 19:22:56 -07003023 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003024 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3025 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003026 }
John Kessenich31ed4832015-09-09 17:51:38 -06003027
John Kessenichead86222018-03-28 18:01:20 -06003028 // Do the outer dimension, which might not be known for a runtime-sized array.
3029 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3030 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003031 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003032 else {
3033 if (!lastBufferBlockMember) {
3034 builder.addExtension("SPV_EXT_descriptor_indexing");
3035 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3036 }
John Kessenichead86222018-03-28 18:01:20 -06003037 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003038 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003039 if (stride > 0)
3040 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003041 }
3042
3043 return spvType;
3044}
3045
John Kessenich0e737842017-03-24 18:38:16 -06003046// TODO: this functionality should exist at a higher level, in creating the AST
3047//
3048// Identify interface members that don't have their required extension turned on.
3049//
3050bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3051{
Chao Chen3c366992018-09-19 11:41:59 -07003052#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003053 auto& extensions = glslangIntermediate->getRequestedExtensions();
3054
Rex Xubcf291a2017-03-29 23:01:36 +08003055 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3056 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3057 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003058 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3059 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3060 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003061
3062 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3063 if (member.getFieldName() == "gl_ViewportMask" &&
3064 extensions.find("GL_NV_viewport_array2") == extensions.end())
3065 return true;
3066 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3067 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3068 return true;
3069 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3070 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3071 return true;
3072 }
3073#endif
John Kessenich0e737842017-03-24 18:38:16 -06003074
3075 return false;
3076};
3077
John Kessenich6090df02016-06-30 21:18:02 -06003078// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3079// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3080// Mutually recursive with convertGlslangToSpvType().
3081spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3082 const glslang::TTypeList* glslangMembers,
3083 glslang::TLayoutPacking explicitLayout,
3084 const glslang::TQualifier& qualifier)
3085{
3086 // Create a vector of struct types for SPIR-V to consume
3087 std::vector<spv::Id> spvMembers;
3088 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 -06003089 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3090 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3091 if (glslangMember.hiddenMember()) {
3092 ++memberDelta;
3093 if (type.getBasicType() == glslang::EbtBlock)
3094 memberRemapper[glslangMembers][i] = -1;
3095 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003096 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003097 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003098 if (filterMember(glslangMember))
3099 continue;
3100 }
John Kessenich6090df02016-06-30 21:18:02 -06003101 // modify just this child's view of the qualifier
3102 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3103 InheritQualifiers(memberQualifier, qualifier);
3104
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003105 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003106 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003107 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003108
3109 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003110 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3111 i == (int)glslangMembers->size() - 1;
3112 spvMembers.push_back(
3113 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003114 }
3115 }
3116
3117 // Make the SPIR-V type
3118 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003119 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003120 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3121
3122 // Decorate it
3123 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3124
3125 return spvType;
3126}
3127
3128void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3129 const glslang::TTypeList* glslangMembers,
3130 glslang::TLayoutPacking explicitLayout,
3131 const glslang::TQualifier& qualifier,
3132 spv::Id spvType)
3133{
3134 // Name and decorate the non-hidden members
3135 int offset = -1;
3136 int locationOffset = 0; // for use within the members of this struct
3137 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3138 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3139 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003140 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003141 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003142 if (filterMember(glslangMember))
3143 continue;
3144 }
John Kessenich6090df02016-06-30 21:18:02 -06003145
3146 // modify just this child's view of the qualifier
3147 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3148 InheritQualifiers(memberQualifier, qualifier);
3149
3150 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003151 if (member < 0)
3152 continue;
3153
3154 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3155 builder.addMemberDecoration(spvType, member,
3156 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3157 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3158 // Add interpolation and auxiliary storage decorations only to
3159 // top-level members of Input and Output storage classes
3160 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3161 type.getQualifier().storage == glslang::EvqVaryingOut) {
3162 if (type.getBasicType() == glslang::EbtBlock ||
3163 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3164 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3165 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003166#ifdef NV_EXTENSIONS
3167 addMeshNVDecoration(spvType, member, memberQualifier);
3168#endif
John Kessenich6090df02016-06-30 21:18:02 -06003169 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003170 }
3171 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003172
John Kessenich5d610ee2018-03-07 18:05:55 -07003173 if (type.getBasicType() == glslang::EbtBlock &&
3174 qualifier.storage == glslang::EvqBuffer) {
3175 // Add memory decorations only to top-level members of shader storage block
3176 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003177 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003178 for (unsigned int i = 0; i < memory.size(); ++i)
3179 builder.addMemberDecoration(spvType, member, memory[i]);
3180 }
John Kessenich6090df02016-06-30 21:18:02 -06003181
John Kessenich5d610ee2018-03-07 18:05:55 -07003182 // Location assignment was already completed correctly by the front end,
3183 // just track whether a member needs to be decorated.
3184 // Ignore member locations if the container is an array, as that's
3185 // ill-specified and decisions have been made to not allow this.
3186 if (! type.isArray() && memberQualifier.hasLocation())
3187 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003188
John Kessenich5d610ee2018-03-07 18:05:55 -07003189 if (qualifier.hasLocation()) // track for upcoming inheritance
3190 locationOffset += glslangIntermediate->computeTypeLocationSize(
3191 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003192
John Kessenich5d610ee2018-03-07 18:05:55 -07003193 // component, XFB, others
3194 if (glslangMember.getQualifier().hasComponent())
3195 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3196 glslangMember.getQualifier().layoutComponent);
3197 if (glslangMember.getQualifier().hasXfbOffset())
3198 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3199 glslangMember.getQualifier().layoutXfbOffset);
3200 else if (explicitLayout != glslang::ElpNone) {
3201 // figure out what to do with offset, which is accumulating
3202 int nextOffset;
3203 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3204 if (offset >= 0)
3205 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3206 offset = nextOffset;
3207 }
John Kessenich6090df02016-06-30 21:18:02 -06003208
John Kessenich5d610ee2018-03-07 18:05:55 -07003209 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3210 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3211 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003212
John Kessenich5d610ee2018-03-07 18:05:55 -07003213 // built-in variable decorations
3214 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3215 if (builtIn != spv::BuiltInMax)
3216 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003217
John Kessenich5611c6d2018-04-05 11:25:02 -06003218 // nonuniform
3219 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3220
John Kessenichead86222018-03-28 18:01:20 -06003221 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3222 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3223 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3224 memberQualifier.semanticName);
3225 }
3226
chaoc771d89f2017-01-13 01:10:53 -08003227#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003228 if (builtIn == spv::BuiltInLayer) {
3229 // SPV_NV_viewport_array2 extension
3230 if (glslangMember.getQualifier().layoutViewportRelative){
3231 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3232 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3233 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003234 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003235 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3236 builder.addMemberDecoration(spvType, member,
3237 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3238 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3239 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3240 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003241 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003242 }
3243 if (glslangMember.getQualifier().layoutPassthrough) {
3244 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3245 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3246 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3247 }
chaoc771d89f2017-01-13 01:10:53 -08003248#endif
John Kessenich6090df02016-06-30 21:18:02 -06003249 }
3250
3251 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003252 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3253 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003254 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3255 builder.addCapability(spv::CapabilityGeometryStreams);
3256 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3257 }
John Kessenich6090df02016-06-30 21:18:02 -06003258}
3259
John Kessenich6c292d32016-02-15 20:58:50 -07003260// Turn the expression forming the array size into an id.
3261// This is not quite trivial, because of specialization constants.
3262// Sometimes, a raw constant is turned into an Id, and sometimes
3263// a specialization constant expression is.
3264spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3265{
3266 // First, see if this is sized with a node, meaning a specialization constant:
3267 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3268 if (specNode != nullptr) {
3269 builder.clearAccessChain();
3270 specNode->traverse(this);
3271 return accessChainLoad(specNode->getAsTyped()->getType());
3272 }
qining25262b32016-05-06 17:25:16 -04003273
John Kessenich6c292d32016-02-15 20:58:50 -07003274 // Otherwise, need a compile-time (front end) size, get it:
3275 int size = arraySizes.getDimSize(dim);
3276 assert(size > 0);
3277 return builder.makeUintConstant(size);
3278}
3279
John Kessenich103bef92016-02-08 21:38:15 -07003280// Wrap the builder's accessChainLoad to:
3281// - localize handling of RelaxedPrecision
3282// - use the SPIR-V inferred type instead of another conversion of the glslang type
3283// (avoids unnecessary work and possible type punning for structures)
3284// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003285spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3286{
John Kessenich103bef92016-02-08 21:38:15 -07003287 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003288
3289 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3290 coherentFlags |= TranslateCoherent(type);
3291
John Kessenich5611c6d2018-04-05 11:25:02 -06003292 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003293 TranslateNonUniformDecoration(type.getQualifier()),
3294 nominalTypeId,
3295 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3296 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003297
3298 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003299 if (type.getBasicType() == glslang::EbtBool) {
3300 if (builder.isScalarType(nominalTypeId)) {
3301 // Conversion for bool
3302 spv::Id boolType = builder.makeBoolType();
3303 if (nominalTypeId != boolType)
3304 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3305 } else if (builder.isVectorType(nominalTypeId)) {
3306 // Conversion for bvec
3307 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3308 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3309 if (nominalTypeId != bvecType)
3310 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3311 }
3312 }
John Kessenich103bef92016-02-08 21:38:15 -07003313
3314 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003315}
3316
Rex Xu27253232016-02-23 17:51:09 +08003317// Wrap the builder's accessChainStore to:
3318// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003319//
3320// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003321void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3322{
3323 // Need to convert to abstract types when necessary
3324 if (type.getBasicType() == glslang::EbtBool) {
3325 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3326
3327 if (builder.isScalarType(nominalTypeId)) {
3328 // Conversion for bool
3329 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003330 if (nominalTypeId != boolType) {
3331 // keep these outside arguments, for determinant order-of-evaluation
3332 spv::Id one = builder.makeUintConstant(1);
3333 spv::Id zero = builder.makeUintConstant(0);
3334 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3335 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003336 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003337 } else if (builder.isVectorType(nominalTypeId)) {
3338 // Conversion for bvec
3339 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3340 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003341 if (nominalTypeId != bvecType) {
3342 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003343 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3344 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3345 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003346 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003347 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3348 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003349 }
3350 }
3351
Jeff Bolz36831c92018-09-05 10:11:41 -05003352 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3353 coherentFlags |= TranslateCoherent(type);
3354
3355 builder.accessChainStore(rvalue,
3356 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3357 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003358}
3359
John Kessenich4bf71552016-09-02 11:20:21 -06003360// For storing when types match at the glslang level, but not might match at the
3361// SPIR-V level.
3362//
3363// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003364// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003365// as in a member-decorated way.
3366//
3367// NOTE: This function can handle any store request; if it's not special it
3368// simplifies to a simple OpStore.
3369//
3370// Implicitly uses the existing builder.accessChain as the storage target.
3371void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3372{
John Kessenichb3e24e42016-09-11 12:33:43 -06003373 // we only do the complex path here if it's an aggregate
3374 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003375 accessChainStore(type, rValue);
3376 return;
3377 }
3378
John Kessenichb3e24e42016-09-11 12:33:43 -06003379 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003380 spv::Id rType = builder.getTypeId(rValue);
3381 spv::Id lValue = builder.accessChainGetLValue();
3382 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3383 if (lType == rType) {
3384 accessChainStore(type, rValue);
3385 return;
3386 }
3387
John Kessenichb3e24e42016-09-11 12:33:43 -06003388 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003389 // where the two types were the same type in GLSL. This requires member
3390 // by member copy, recursively.
3391
John Kessenichb3e24e42016-09-11 12:33:43 -06003392 // If an array, copy element by element.
3393 if (type.isArray()) {
3394 glslang::TType glslangElementType(type, 0);
3395 spv::Id elementRType = builder.getContainedTypeId(rType);
3396 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3397 // get the source member
3398 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003399
John Kessenichb3e24e42016-09-11 12:33:43 -06003400 // set up the target storage
3401 builder.clearAccessChain();
3402 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003403 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003404
John Kessenichb3e24e42016-09-11 12:33:43 -06003405 // store the member
3406 multiTypeStore(glslangElementType, elementRValue);
3407 }
3408 } else {
3409 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003410
John Kessenichb3e24e42016-09-11 12:33:43 -06003411 // loop over structure members
3412 const glslang::TTypeList& members = *type.getStruct();
3413 for (int m = 0; m < (int)members.size(); ++m) {
3414 const glslang::TType& glslangMemberType = *members[m].type;
3415
3416 // get the source member
3417 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3418 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3419
3420 // set up the target storage
3421 builder.clearAccessChain();
3422 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003423 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003424
3425 // store the member
3426 multiTypeStore(glslangMemberType, memberRValue);
3427 }
John Kessenich4bf71552016-09-02 11:20:21 -06003428 }
3429}
3430
John Kessenichf85e8062015-12-19 13:57:10 -07003431// Decide whether or not this type should be
3432// decorated with offsets and strides, and if so
3433// whether std140 or std430 rules should be applied.
3434glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003435{
John Kessenichf85e8062015-12-19 13:57:10 -07003436 // has to be a block
3437 if (type.getBasicType() != glslang::EbtBlock)
3438 return glslang::ElpNone;
3439
Chao Chen3c366992018-09-19 11:41:59 -07003440 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003441 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003442 type.getQualifier().storage != glslang::EvqBuffer &&
3443 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003444 return glslang::ElpNone;
3445
3446 // return the layout to use
3447 switch (type.getQualifier().layoutPacking) {
3448 case glslang::ElpStd140:
3449 case glslang::ElpStd430:
3450 return type.getQualifier().layoutPacking;
3451 default:
3452 return glslang::ElpNone;
3453 }
John Kessenich31ed4832015-09-09 17:51:38 -06003454}
3455
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003456// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003457int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003458{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003459 int size;
John Kessenich49987892015-12-29 17:11:44 -07003460 int stride;
3461 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003462
3463 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003464}
3465
John Kessenich49987892015-12-29 17:11:44 -07003466// 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 -07003467// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003468int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003469{
John Kessenich49987892015-12-29 17:11:44 -07003470 glslang::TType elementType;
3471 elementType.shallowCopy(matrixType);
3472 elementType.clearArraySizes();
3473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003474 int size;
John Kessenich49987892015-12-29 17:11:44 -07003475 int stride;
3476 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3477
3478 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003479}
3480
John Kessenich5e4b1242015-08-06 22:53:06 -06003481// Given a member type of a struct, realign the current offset for it, and compute
3482// the next (not yet aligned) offset for the next member, which will get aligned
3483// on the next call.
3484// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3485// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3486// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003487void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003488 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003489{
3490 // this will get a positive value when deemed necessary
3491 nextOffset = -1;
3492
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 // override anything in currentOffset with user-set offset
3494 if (memberType.getQualifier().hasOffset())
3495 currentOffset = memberType.getQualifier().layoutOffset;
3496
3497 // It could be that current linker usage in glslang updated all the layoutOffset,
3498 // in which case the following code does not matter. But, that's not quite right
3499 // once cross-compilation unit GLSL validation is done, as the original user
3500 // settings are needed in layoutOffset, and then the following will come into play.
3501
John Kessenichf85e8062015-12-19 13:57:10 -07003502 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 if (! memberType.getQualifier().hasOffset())
3504 currentOffset = -1;
3505
3506 return;
3507 }
3508
John Kessenichf85e8062015-12-19 13:57:10 -07003509 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 if (currentOffset < 0)
3511 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003512
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3514 // but possibly not yet correctly aligned.
3515
3516 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003517 int dummyStride;
3518 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003519
3520 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003521 // TODO: make this consistent in early phases of code:
3522 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3523 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3524 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003525 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003526 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003527 int dummySize;
3528 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3529 if (componentAlignment <= 4)
3530 memberAlignment = componentAlignment;
3531 }
3532
3533 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003534 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003535
3536 // Bump up to vec4 if there is a bad straddle
3537 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3538 glslang::RoundToPow2(currentOffset, 16);
3539
John Kessenich5e4b1242015-08-06 22:53:06 -06003540 nextOffset = currentOffset + memberSize;
3541}
3542
David Netoa901ffe2016-06-08 14:11:40 +01003543void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003544{
David Netoa901ffe2016-06-08 14:11:40 +01003545 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3546 switch (glslangBuiltIn)
3547 {
3548 case glslang::EbvClipDistance:
3549 case glslang::EbvCullDistance:
3550 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003551#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003552 case glslang::EbvViewportMaskNV:
3553 case glslang::EbvSecondaryPositionNV:
3554 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003555 case glslang::EbvPositionPerViewNV:
3556 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003557 case glslang::EbvTaskCountNV:
3558 case glslang::EbvPrimitiveCountNV:
3559 case glslang::EbvPrimitiveIndicesNV:
3560 case glslang::EbvClipDistancePerViewNV:
3561 case glslang::EbvCullDistancePerViewNV:
3562 case glslang::EbvLayerPerViewNV:
3563 case glslang::EbvMeshViewCountNV:
3564 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003565#endif
David Netoa901ffe2016-06-08 14:11:40 +01003566 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3567 // Alternately, we could just call this for any glslang built-in, since the
3568 // capability already guards against duplicates.
3569 TranslateBuiltInDecoration(glslangBuiltIn, false);
3570 break;
3571 default:
3572 // Capabilities were already generated when the struct was declared.
3573 break;
3574 }
John Kessenichebb50532016-05-16 19:22:05 -06003575}
3576
John Kessenich6fccb3c2016-09-19 16:01:41 -06003577bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003578{
John Kessenicheee9d532016-09-19 18:09:30 -06003579 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003580}
3581
John Kessenichd41993d2017-09-10 15:21:05 -06003582// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003583// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3584// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003585bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003586{
John Kessenich6a14f782017-12-04 02:48:10 -07003587 assert(qualifier == glslang::EvqIn ||
3588 qualifier == glslang::EvqOut ||
3589 qualifier == glslang::EvqInOut ||
3590 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003591 return qualifier != glslang::EvqConstReadOnly;
3592}
3593
3594// Is parameter pass-by-original?
3595bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3596 bool implicitThisParam)
3597{
3598 if (implicitThisParam) // implicit this
3599 return true;
3600 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003601 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003602 return paramType.containsOpaque() || // sampler, etc.
3603 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3604}
3605
John Kessenich140f3df2015-06-26 16:58:36 -06003606// Make all the functions, skeletally, without actually visiting their bodies.
3607void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3608{
Jeff Bolz36831c92018-09-05 10:11:41 -05003609 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003610 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3611 if (paramPrecision != spv::NoPrecision)
3612 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003613 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003614 };
3615
John Kessenich140f3df2015-06-26 16:58:36 -06003616 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3617 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003618 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003619 continue;
3620
3621 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003622 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003623 //
qining25262b32016-05-06 17:25:16 -04003624 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003625 // function. What it is an address of varies:
3626 //
John Kessenich4bf71552016-09-02 11:20:21 -06003627 // - "in" parameters not marked as "const" can be written to without modifying the calling
3628 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003629 //
3630 // - "const in" parameters can just be the r-value, as no writes need occur.
3631 //
John Kessenich4bf71552016-09-02 11:20:21 -06003632 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3633 // 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 -06003634
3635 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003636 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003637 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3638
John Kessenichfad62972017-07-18 02:35:46 -06003639 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3640 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003641
John Kessenichfad62972017-07-18 02:35:46 -06003642 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003643 for (int p = 0; p < (int)parameters.size(); ++p) {
3644 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3645 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003646 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003647 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003648 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003649 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3650 else
John Kessenich4bf71552016-09-02 11:20:21 -06003651 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003652 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003653 paramTypes.push_back(typeId);
3654 }
3655
3656 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003657 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3658 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003659 glslFunction->getName().c_str(), paramTypes,
3660 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003661 if (implicitThis)
3662 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003663
3664 // Track function to emit/call later
3665 functionMap[glslFunction->getName().c_str()] = function;
3666
3667 // Set the parameter id's
3668 for (int p = 0; p < (int)parameters.size(); ++p) {
3669 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3670 // give a name too
3671 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3672 }
3673 }
3674}
3675
3676// Process all the initializers, while skipping the functions and link objects
3677void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3678{
3679 builder.setBuildPoint(shaderEntry->getLastBlock());
3680 for (int i = 0; i < (int)initializers.size(); ++i) {
3681 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3682 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3683
3684 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003685 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003686 initializer->traverse(this);
3687 }
3688 }
3689}
3690
3691// Process all the functions, while skipping initializers.
3692void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3693{
3694 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3695 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003696 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003697 node->traverse(this);
3698 }
3699}
3700
3701void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3702{
qining25262b32016-05-06 17:25:16 -04003703 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003704 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003705 currentFunction = functionMap[node->getName().c_str()];
3706 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003707 builder.setBuildPoint(functionBlock);
3708}
3709
Rex Xu04db3f52015-09-16 11:44:02 +08003710void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003711{
Rex Xufc618912015-09-09 16:42:49 +08003712 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003713
3714 glslang::TSampler sampler = {};
3715 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003716#ifdef AMD_EXTENSIONS
3717 bool f16ShadowCompare = false;
3718#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003719 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003720 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3721 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003722#ifdef AMD_EXTENSIONS
3723 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3724#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003725 }
3726
John Kessenich140f3df2015-06-26 16:58:36 -06003727 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3728 builder.clearAccessChain();
3729 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003730
3731 // Special case l-value operands
3732 bool lvalue = false;
3733 switch (node.getOp()) {
3734 case glslang::EOpImageAtomicAdd:
3735 case glslang::EOpImageAtomicMin:
3736 case glslang::EOpImageAtomicMax:
3737 case glslang::EOpImageAtomicAnd:
3738 case glslang::EOpImageAtomicOr:
3739 case glslang::EOpImageAtomicXor:
3740 case glslang::EOpImageAtomicExchange:
3741 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003742 case glslang::EOpImageAtomicLoad:
3743 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003744 if (i == 0)
3745 lvalue = true;
3746 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003747 case glslang::EOpSparseImageLoad:
3748 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3749 lvalue = true;
3750 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003751#ifdef AMD_EXTENSIONS
3752 case glslang::EOpSparseTexture:
3753 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3754 lvalue = true;
3755 break;
3756 case glslang::EOpSparseTextureClamp:
3757 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3758 lvalue = true;
3759 break;
3760 case glslang::EOpSparseTextureLod:
3761 case glslang::EOpSparseTextureOffset:
3762 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3763 lvalue = true;
3764 break;
3765#else
Rex Xu48edadf2015-12-31 16:11:41 +08003766 case glslang::EOpSparseTexture:
3767 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3768 lvalue = true;
3769 break;
3770 case glslang::EOpSparseTextureClamp:
3771 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3772 lvalue = true;
3773 break;
3774 case glslang::EOpSparseTextureLod:
3775 case glslang::EOpSparseTextureOffset:
3776 if (i == 3)
3777 lvalue = true;
3778 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003779#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003780 case glslang::EOpSparseTextureFetch:
3781 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3782 lvalue = true;
3783 break;
3784 case glslang::EOpSparseTextureFetchOffset:
3785 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3786 lvalue = true;
3787 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003788#ifdef AMD_EXTENSIONS
3789 case glslang::EOpSparseTextureLodOffset:
3790 case glslang::EOpSparseTextureGrad:
3791 case glslang::EOpSparseTextureOffsetClamp:
3792 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3793 lvalue = true;
3794 break;
3795 case glslang::EOpSparseTextureGradOffset:
3796 case glslang::EOpSparseTextureGradClamp:
3797 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3798 lvalue = true;
3799 break;
3800 case glslang::EOpSparseTextureGradOffsetClamp:
3801 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3802 lvalue = true;
3803 break;
3804#else
Rex Xu48edadf2015-12-31 16:11:41 +08003805 case glslang::EOpSparseTextureLodOffset:
3806 case glslang::EOpSparseTextureGrad:
3807 case glslang::EOpSparseTextureOffsetClamp:
3808 if (i == 4)
3809 lvalue = true;
3810 break;
3811 case glslang::EOpSparseTextureGradOffset:
3812 case glslang::EOpSparseTextureGradClamp:
3813 if (i == 5)
3814 lvalue = true;
3815 break;
3816 case glslang::EOpSparseTextureGradOffsetClamp:
3817 if (i == 6)
3818 lvalue = true;
3819 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003820#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003821 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003822 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3823 lvalue = true;
3824 break;
3825 case glslang::EOpSparseTextureGatherOffset:
3826 case glslang::EOpSparseTextureGatherOffsets:
3827 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3828 lvalue = true;
3829 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003830#ifdef AMD_EXTENSIONS
3831 case glslang::EOpSparseTextureGatherLod:
3832 if (i == 3)
3833 lvalue = true;
3834 break;
3835 case glslang::EOpSparseTextureGatherLodOffset:
3836 case glslang::EOpSparseTextureGatherLodOffsets:
3837 if (i == 4)
3838 lvalue = true;
3839 break;
Rex Xu129799a2017-07-05 17:23:28 +08003840 case glslang::EOpSparseImageLoadLod:
3841 if (i == 3)
3842 lvalue = true;
3843 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003844#endif
Chao Chen3a137962018-09-19 11:41:27 -07003845#ifdef NV_EXTENSIONS
3846 case glslang::EOpImageSampleFootprintNV:
3847 if (i == 4)
3848 lvalue = true;
3849 break;
3850 case glslang::EOpImageSampleFootprintClampNV:
3851 case glslang::EOpImageSampleFootprintLodNV:
3852 if (i == 5)
3853 lvalue = true;
3854 break;
3855 case glslang::EOpImageSampleFootprintGradNV:
3856 if (i == 6)
3857 lvalue = true;
3858 break;
3859 case glslang::EOpImageSampleFootprintGradClampNV:
3860 if (i == 7)
3861 lvalue = true;
3862 break;
3863#endif
Rex Xufc618912015-09-09 16:42:49 +08003864 default:
3865 break;
3866 }
3867
Rex Xu6b86d492015-09-16 17:48:22 +08003868 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003869 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003870 else
John Kessenich32cfd492016-02-02 12:37:46 -07003871 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003872 }
3873}
3874
John Kessenichfc51d282015-08-19 13:34:18 -06003875void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003876{
John Kessenichfc51d282015-08-19 13:34:18 -06003877 builder.clearAccessChain();
3878 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003879 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003880}
John Kessenich140f3df2015-06-26 16:58:36 -06003881
John Kessenichfc51d282015-08-19 13:34:18 -06003882spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3883{
John Kesseniche485c7a2017-05-31 18:50:53 -06003884 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003885 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003886
3887 builder.setLine(node->getLoc().line);
3888
John Kessenichfc51d282015-08-19 13:34:18 -06003889 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003890
3891 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3892 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3893 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003894#ifdef AMD_EXTENSIONS
3895 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3896 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3897 : false;
3898#endif
3899
John Kessenichfc51d282015-08-19 13:34:18 -06003900 std::vector<spv::Id> arguments;
3901 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003902 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003903 else
3904 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003905 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003906
3907 spv::Builder::TextureParameters params = { };
3908 params.sampler = arguments[0];
3909
Rex Xu04db3f52015-09-16 11:44:02 +08003910 glslang::TCrackedTextureOp cracked;
3911 node->crackTexture(sampler, cracked);
3912
amhagan05506bb2017-06-13 16:53:02 -04003913 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003914
John Kessenichfc51d282015-08-19 13:34:18 -06003915 // Check for queries
3916 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003917 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3918 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003919 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003920
John Kessenichfc51d282015-08-19 13:34:18 -06003921 switch (node->getOp()) {
3922 case glslang::EOpImageQuerySize:
3923 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003924 if (arguments.size() > 1) {
3925 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003926 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003927 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003928 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003929 case glslang::EOpImageQuerySamples:
3930 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003931 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003932 case glslang::EOpTextureQueryLod:
3933 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003934 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003935 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003936 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003937 case glslang::EOpSparseTexelsResident:
3938 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003939 default:
3940 assert(0);
3941 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003942 }
John Kessenich140f3df2015-06-26 16:58:36 -06003943 }
3944
LoopDawg4425f242018-02-18 11:40:01 -07003945 int components = node->getType().getVectorSize();
3946
3947 if (node->getOp() == glslang::EOpTextureFetch) {
3948 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3949 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3950 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3951 // here around e.g. which ones return scalars or other types.
3952 components = 4;
3953 }
3954
3955 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3956
3957 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3958
Rex Xufc618912015-09-09 16:42:49 +08003959 // Check for image functions other than queries
3960 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003961 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003962 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003963 spv::IdImmediate image = { true, *(opIt++) };
3964 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003965
3966 // Handle subpass operations
3967 // TODO: GLSL should change to have the "MS" only on the type rather than the
3968 // built-in function.
3969 if (cracked.subpass) {
3970 // add on the (0,0) coordinate
3971 spv::Id zero = builder.makeIntConstant(0);
3972 std::vector<spv::Id> comps;
3973 comps.push_back(zero);
3974 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003975 spv::IdImmediate coord = { true,
3976 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3977 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003978 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003979 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3980 operands.push_back(imageOperands);
3981 spv::IdImmediate imageOperand = { true, *(opIt++) };
3982 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003983 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003984 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3985 builder.setPrecision(result, precision);
3986 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003987 }
3988
John Kessenich149afc32018-08-14 13:31:43 -06003989 spv::IdImmediate coord = { true, *(opIt++) };
3990 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003991#ifdef AMD_EXTENSIONS
3992 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3993#else
John Kessenich56bab042015-09-16 10:54:31 -06003994 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003995#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003996 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003997 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003998 mask = mask | spv::ImageOperandsSampleMask;
3999 }
Rex Xu129799a2017-07-05 17:23:28 +08004000#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004001 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004002 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4003 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004004 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004005 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004006#endif
4007 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4008 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4009 if (mask) {
4010 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4011 operands.push_back(imageOperands);
4012 }
4013 if (mask & spv::ImageOperandsSampleMask) {
4014 spv::IdImmediate imageOperand = { true, *opIt++ };
4015 operands.push_back(imageOperand);
4016 }
4017#ifdef AMD_EXTENSIONS
4018 if (mask & spv::ImageOperandsLodMask) {
4019 spv::IdImmediate imageOperand = { true, *opIt++ };
4020 operands.push_back(imageOperand);
4021 }
4022#endif
4023 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4024 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4025 operands.push_back(imageOperand);
4026 }
4027
John Kessenich149afc32018-08-14 13:31:43 -06004028 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004029 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004030
John Kessenich149afc32018-08-14 13:31:43 -06004031 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004032 builder.setPrecision(result[0], precision);
4033
4034 // If needed, add a conversion constructor to the proper size.
4035 if (components != node->getType().getVectorSize())
4036 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4037
4038 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004039#ifdef AMD_EXTENSIONS
4040 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4041#else
John Kessenich56bab042015-09-16 10:54:31 -06004042 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004043#endif
Rex Xu129799a2017-07-05 17:23:28 +08004044
Jeff Bolz36831c92018-09-05 10:11:41 -05004045 // Push the texel value before the operands
4046#ifdef AMD_EXTENSIONS
4047 if (sampler.ms || cracked.lod) {
4048#else
4049 if (sampler.ms) {
4050#endif
John Kessenich149afc32018-08-14 13:31:43 -06004051 spv::IdImmediate texel = { true, *(opIt + 1) };
4052 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004053 } else {
4054 spv::IdImmediate texel = { true, *opIt };
4055 operands.push_back(texel);
4056 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004057
4058 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4059 if (sampler.ms) {
4060 mask = mask | spv::ImageOperandsSampleMask;
4061 }
4062#ifdef AMD_EXTENSIONS
4063 if (cracked.lod) {
4064 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4065 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4066 mask = mask | spv::ImageOperandsLodMask;
4067 }
4068#endif
4069 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4070 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4071 if (mask) {
4072 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4073 operands.push_back(imageOperands);
4074 }
4075 if (mask & spv::ImageOperandsSampleMask) {
4076 spv::IdImmediate imageOperand = { true, *opIt++ };
4077 operands.push_back(imageOperand);
4078 }
4079#ifdef AMD_EXTENSIONS
4080 if (mask & spv::ImageOperandsLodMask) {
4081 spv::IdImmediate imageOperand = { true, *opIt++ };
4082 operands.push_back(imageOperand);
4083 }
4084#endif
4085 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4086 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4087 operands.push_back(imageOperand);
4088 }
4089
John Kessenich56bab042015-09-16 10:54:31 -06004090 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004091 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004092 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004093 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004094#ifdef AMD_EXTENSIONS
4095 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4096#else
Rex Xu5eafa472016-02-19 22:24:03 +08004097 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004098#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004099 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004100 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004101 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4102
Jeff Bolz36831c92018-09-05 10:11:41 -05004103 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004104 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004105 mask = mask | spv::ImageOperandsSampleMask;
4106 }
Rex Xu129799a2017-07-05 17:23:28 +08004107#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004108 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004109 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4110 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4111
Jeff Bolz36831c92018-09-05 10:11:41 -05004112 mask = mask | spv::ImageOperandsLodMask;
4113 }
4114#endif
4115 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4116 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4117 if (mask) {
4118 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004119 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004120 }
4121 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004122 spv::IdImmediate imageOperand = { true, *opIt++ };
4123 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004124 }
4125#ifdef AMD_EXTENSIONS
4126 if (mask & spv::ImageOperandsLodMask) {
4127 spv::IdImmediate imageOperand = { true, *opIt++ };
4128 operands.push_back(imageOperand);
4129 }
Rex Xu129799a2017-07-05 17:23:28 +08004130#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004131 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4132 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4133 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004134 }
4135
4136 // Create the return type that was a special structure
4137 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004138 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004139 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4140 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4141
4142 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4143
4144 // Decode the return type
4145 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4146 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004147 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004148 // Process image atomic operations
4149
4150 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4151 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004152 // For non-MS, the sample value should be 0
4153 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4154 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004155
Jeff Bolz36831c92018-09-05 10:11:41 -05004156 spv::Id resultTypeId;
4157 // imageAtomicStore has a void return type so base the pointer type on
4158 // the type of the value operand.
4159 if (node->getOp() == glslang::EOpImageAtomicStore) {
4160 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4161 } else {
4162 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4163 }
John Kessenich56bab042015-09-16 10:54:31 -06004164 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004165
4166 std::vector<spv::Id> operands;
4167 operands.push_back(pointer);
4168 for (; opIt != arguments.end(); ++opIt)
4169 operands.push_back(*opIt);
4170
John Kessenich8c8505c2016-07-26 12:50:38 -06004171 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004172 }
4173 }
4174
amhagan05506bb2017-06-13 16:53:02 -04004175#ifdef AMD_EXTENSIONS
4176 // Check for fragment mask functions other than queries
4177 if (cracked.fragMask) {
4178 assert(sampler.ms);
4179
4180 auto opIt = arguments.begin();
4181 std::vector<spv::Id> operands;
4182
4183 // Extract the image if necessary
4184 if (builder.isSampledImage(params.sampler))
4185 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4186
4187 operands.push_back(params.sampler);
4188 ++opIt;
4189
4190 if (sampler.isSubpass()) {
4191 // add on the (0,0) coordinate
4192 spv::Id zero = builder.makeIntConstant(0);
4193 std::vector<spv::Id> comps;
4194 comps.push_back(zero);
4195 comps.push_back(zero);
4196 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4197 }
4198
4199 for (; opIt != arguments.end(); ++opIt)
4200 operands.push_back(*opIt);
4201
4202 spv::Op fragMaskOp = spv::OpNop;
4203 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4204 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4205 else if (node->getOp() == glslang::EOpFragmentFetch)
4206 fragMaskOp = spv::OpFragmentFetchAMD;
4207
4208 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4209 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4210 return builder.createOp(fragMaskOp, resultType(), operands);
4211 }
4212#endif
4213
Rex Xufc618912015-09-09 16:42:49 +08004214 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004215 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004216#ifdef NV_EXTENSIONS
4217 bool imageFootprint = node->isImageFootprint();
4218#endif
4219
Rex Xu71519fe2015-11-11 15:35:47 +08004220 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4221
John Kessenichfc51d282015-08-19 13:34:18 -06004222 // check for bias argument
4223 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004224#ifdef AMD_EXTENSIONS
4225 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4226#else
Rex Xu71519fe2015-11-11 15:35:47 +08004227 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004228#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004229 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004230#ifdef AMD_EXTENSIONS
4231 if (cracked.gather)
4232 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004233
4234 if (f16ShadowCompare)
4235 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004236#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004237 if (cracked.offset)
4238 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004239#ifdef AMD_EXTENSIONS
4240 else if (cracked.offsets)
4241 ++nonBiasArgCount;
4242#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004243 if (cracked.grad)
4244 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004245 if (cracked.lodClamp)
4246 ++nonBiasArgCount;
4247 if (sparse)
4248 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004249#ifdef NV_EXTENSIONS
4250 if (imageFootprint)
4251 //Following three extra arguments
4252 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4253 nonBiasArgCount += 3;
4254#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004255 if ((int)arguments.size() > nonBiasArgCount)
4256 bias = true;
4257 }
4258
John Kessenicha5c33d62016-06-02 23:45:21 -06004259 // See if the sampler param should really be just the SPV image part
4260 if (cracked.fetch) {
4261 // a fetch needs to have the image extracted first
4262 if (builder.isSampledImage(params.sampler))
4263 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4264 }
4265
Rex Xu225e0fc2016-11-17 17:47:59 +08004266#ifdef AMD_EXTENSIONS
4267 if (cracked.gather) {
4268 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4269 if (bias || cracked.lod ||
4270 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4271 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004272 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004273 }
4274 }
4275#endif
4276
John Kessenichfc51d282015-08-19 13:34:18 -06004277 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004278
John Kessenichfc51d282015-08-19 13:34:18 -06004279 params.coords = arguments[1];
4280 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004281 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004282
4283 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004284#ifdef AMD_EXTENSIONS
4285 if (cubeCompare || f16ShadowCompare) {
4286#else
Rex Xu48edadf2015-12-31 16:11:41 +08004287 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004288#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004289 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004290 ++extraArgs;
4291 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004292 params.Dref = arguments[2];
4293 ++extraArgs;
4294 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004295 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004296 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004297 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004298 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004299 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004300 dRefComp = builder.getNumComponents(params.coords) - 1;
4301 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004302 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4303 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004304
4305 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004306 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004307 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004308 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004309 } else if (glslangIntermediate->getStage() != EShLangFragment
4310#ifdef NV_EXTENSIONS
4311 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4312 && !(glslangIntermediate->getStage() == EShLangCompute &&
4313 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4314#endif
4315 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004316 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4317 noImplicitLod = true;
4318 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004319
4320 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004321 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004322 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004323 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004324 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004325
4326 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004327 if (cracked.grad) {
4328 params.gradX = arguments[2 + extraArgs];
4329 params.gradY = arguments[3 + extraArgs];
4330 extraArgs += 2;
4331 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004332
4333 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004334 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004335 params.offset = arguments[2 + extraArgs];
4336 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004337 } else if (cracked.offsets) {
4338 params.offsets = arguments[2 + extraArgs];
4339 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004340 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004341
4342 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004343 if (cracked.lodClamp) {
4344 params.lodClamp = arguments[2 + extraArgs];
4345 ++extraArgs;
4346 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004347 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004348 if (sparse) {
4349 params.texelOut = arguments[2 + extraArgs];
4350 ++extraArgs;
4351 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004352
John Kessenich76d4dfc2016-06-16 12:43:23 -06004353 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004354 if (cracked.gather && ! sampler.shadow) {
4355 // default component is 0, if missing, otherwise an argument
4356 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004357 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004358 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004359 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004360 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004361 }
Chao Chen3a137962018-09-19 11:41:27 -07004362#ifdef NV_EXTENSIONS
4363 spv::Id resultStruct = spv::NoResult;
4364 if (imageFootprint) {
4365 //Following three extra arguments
4366 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4367 params.granularity = arguments[2 + extraArgs];
4368 params.coarse = arguments[3 + extraArgs];
4369 resultStruct = arguments[4 + extraArgs];
4370 extraArgs += 3;
4371 }
4372#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004373 // bias
4374 if (bias) {
4375 params.bias = arguments[2 + extraArgs];
4376 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004377 }
John Kessenichfc51d282015-08-19 13:34:18 -06004378
Chao Chen3a137962018-09-19 11:41:27 -07004379#ifdef NV_EXTENSIONS
4380 if (imageFootprint) {
4381 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4382 builder.addCapability(spv::CapabilityImageFootprintNV);
4383
4384
4385 //resultStructType(OpenGL type) contains 5 elements:
4386 //struct gl_TextureFootprint2DNV {
4387 // uvec2 anchor;
4388 // uvec2 offset;
4389 // uvec2 mask;
4390 // uint lod;
4391 // uint granularity;
4392 //};
4393 //or
4394 //struct gl_TextureFootprint3DNV {
4395 // uvec3 anchor;
4396 // uvec3 offset;
4397 // uvec2 mask;
4398 // uint lod;
4399 // uint granularity;
4400 //};
4401 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4402 assert(builder.isStructType(resultStructType));
4403
4404 //resType (SPIR-V type) contains 6 elements:
4405 //Member 0 must be a Boolean type scalar(LOD),
4406 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4407 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4408 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4409 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4410 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4411 std::vector<spv::Id> members;
4412 members.push_back(resultType());
4413 for (int i = 0; i < 5; i++) {
4414 members.push_back(builder.getContainedTypeId(resultStructType, i));
4415 }
4416 spv::Id resType = builder.makeStructType(members, "ResType");
4417
4418 //call ImageFootprintNV
4419 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4420
4421 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4422 for (int i = 0; i < 5; i++) {
4423 builder.clearAccessChain();
4424 builder.setAccessChainLValue(resultStruct);
4425
4426 //Accessing to a struct we created, no coherent flag is set
4427 spv::Builder::AccessChain::CoherentFlags flags;
4428 flags.clear();
4429
4430 builder.accessChainPush(builder.makeIntConstant(i), flags);
4431 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4432 }
4433 return builder.createCompositeExtract(res, resultType(), 0);
4434 }
4435#endif
4436
John Kessenich65336482016-06-16 14:06:26 -06004437 // projective component (might not to move)
4438 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4439 // are divided by the last component of P."
4440 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4441 // unused components will appear after all used components."
4442 if (cracked.proj) {
4443 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4444 int projTargetComp;
4445 switch (sampler.dim) {
4446 case glslang::Esd1D: projTargetComp = 1; break;
4447 case glslang::Esd2D: projTargetComp = 2; break;
4448 case glslang::EsdRect: projTargetComp = 2; break;
4449 default: projTargetComp = projSourceComp; break;
4450 }
4451 // copy the projective coordinate if we have to
4452 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004453 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004454 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4455 projSourceComp);
4456 params.coords = builder.createCompositeInsert(projComp, params.coords,
4457 builder.getTypeId(params.coords), projTargetComp);
4458 }
4459 }
4460
Jeff Bolz36831c92018-09-05 10:11:41 -05004461 // nonprivate
4462 if (imageType.getQualifier().nonprivate) {
4463 params.nonprivate = true;
4464 }
4465
4466 // volatile
4467 if (imageType.getQualifier().volatil) {
4468 params.volatil = true;
4469 }
4470
St0fFa1184dd2018-04-09 21:08:14 +02004471 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004472 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004473 );
LoopDawg4425f242018-02-18 11:40:01 -07004474
4475 if (components != node->getType().getVectorSize())
4476 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4477
4478 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004479}
4480
4481spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4482{
4483 // Grab the function's pointer from the previously created function
4484 spv::Function* function = functionMap[node->getName().c_str()];
4485 if (! function)
4486 return 0;
4487
4488 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4489 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4490
4491 // See comments in makeFunctions() for details about the semantics for parameter passing.
4492 //
4493 // These imply we need a four step process:
4494 // 1. Evaluate the arguments
4495 // 2. Allocate and make copies of in, out, and inout arguments
4496 // 3. Make the call
4497 // 4. Copy back the results
4498
John Kessenichd3ed90b2018-05-04 11:43:03 -06004499 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004500 std::vector<spv::Builder::AccessChain> lValues;
4501 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004502 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004503 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004504 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004505 // build l-value
4506 builder.clearAccessChain();
4507 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004508 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004509 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004510 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004511 // save l-value
4512 lValues.push_back(builder.getAccessChain());
4513 } else {
4514 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004515 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004516 }
4517 }
4518
4519 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4520 // copy the original into that space.
4521 //
4522 // Also, build up the list of actual arguments to pass in for the call
4523 int lValueCount = 0;
4524 int rValueCount = 0;
4525 std::vector<spv::Id> spvArgs;
4526 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4527 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004528 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004529 builder.setAccessChain(lValues[lValueCount]);
4530 arg = builder.accessChainGetLValue();
4531 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004532 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004533 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004534 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004535 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4536 // need to copy the input into output space
4537 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004538 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004539 builder.clearAccessChain();
4540 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004541 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004542 }
4543 ++lValueCount;
4544 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004545 // process r-value, which involves a copy for a type mismatch
4546 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4547 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4548 builder.clearAccessChain();
4549 builder.setAccessChainLValue(argCopy);
4550 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4551 arg = builder.createLoad(argCopy);
4552 } else
4553 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004554 ++rValueCount;
4555 }
4556 spvArgs.push_back(arg);
4557 }
4558
4559 // 3. Make the call.
4560 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004561 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004562
4563 // 4. Copy back out an "out" arguments.
4564 lValueCount = 0;
4565 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004566 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004567 ++lValueCount;
4568 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004569 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4570 spv::Id copy = builder.createLoad(spvArgs[a]);
4571 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004572 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004573 }
4574 ++lValueCount;
4575 }
4576 }
4577
4578 return result;
4579}
4580
4581// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004582spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004583 spv::Id typeId, spv::Id left, spv::Id right,
4584 glslang::TBasicType typeProxy, bool reduceComparison)
4585{
John Kessenich66011cb2018-03-06 16:12:04 -07004586 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4587 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004588 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004589
4590 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004591 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004592 bool comparison = false;
4593
4594 switch (op) {
4595 case glslang::EOpAdd:
4596 case glslang::EOpAddAssign:
4597 if (isFloat)
4598 binOp = spv::OpFAdd;
4599 else
4600 binOp = spv::OpIAdd;
4601 break;
4602 case glslang::EOpSub:
4603 case glslang::EOpSubAssign:
4604 if (isFloat)
4605 binOp = spv::OpFSub;
4606 else
4607 binOp = spv::OpISub;
4608 break;
4609 case glslang::EOpMul:
4610 case glslang::EOpMulAssign:
4611 if (isFloat)
4612 binOp = spv::OpFMul;
4613 else
4614 binOp = spv::OpIMul;
4615 break;
4616 case glslang::EOpVectorTimesScalar:
4617 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004618 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004619 if (builder.isVector(right))
4620 std::swap(left, right);
4621 assert(builder.isScalar(right));
4622 needMatchingVectors = false;
4623 binOp = spv::OpVectorTimesScalar;
4624 } else
4625 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004626 break;
4627 case glslang::EOpVectorTimesMatrix:
4628 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004629 binOp = spv::OpVectorTimesMatrix;
4630 break;
4631 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004632 binOp = spv::OpMatrixTimesVector;
4633 break;
4634 case glslang::EOpMatrixTimesScalar:
4635 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004636 binOp = spv::OpMatrixTimesScalar;
4637 break;
4638 case glslang::EOpMatrixTimesMatrix:
4639 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004640 binOp = spv::OpMatrixTimesMatrix;
4641 break;
4642 case glslang::EOpOuterProduct:
4643 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004644 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004645 break;
4646
4647 case glslang::EOpDiv:
4648 case glslang::EOpDivAssign:
4649 if (isFloat)
4650 binOp = spv::OpFDiv;
4651 else if (isUnsigned)
4652 binOp = spv::OpUDiv;
4653 else
4654 binOp = spv::OpSDiv;
4655 break;
4656 case glslang::EOpMod:
4657 case glslang::EOpModAssign:
4658 if (isFloat)
4659 binOp = spv::OpFMod;
4660 else if (isUnsigned)
4661 binOp = spv::OpUMod;
4662 else
4663 binOp = spv::OpSMod;
4664 break;
4665 case glslang::EOpRightShift:
4666 case glslang::EOpRightShiftAssign:
4667 if (isUnsigned)
4668 binOp = spv::OpShiftRightLogical;
4669 else
4670 binOp = spv::OpShiftRightArithmetic;
4671 break;
4672 case glslang::EOpLeftShift:
4673 case glslang::EOpLeftShiftAssign:
4674 binOp = spv::OpShiftLeftLogical;
4675 break;
4676 case glslang::EOpAnd:
4677 case glslang::EOpAndAssign:
4678 binOp = spv::OpBitwiseAnd;
4679 break;
4680 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004681 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004682 binOp = spv::OpLogicalAnd;
4683 break;
4684 case glslang::EOpInclusiveOr:
4685 case glslang::EOpInclusiveOrAssign:
4686 binOp = spv::OpBitwiseOr;
4687 break;
4688 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004689 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004690 binOp = spv::OpLogicalOr;
4691 break;
4692 case glslang::EOpExclusiveOr:
4693 case glslang::EOpExclusiveOrAssign:
4694 binOp = spv::OpBitwiseXor;
4695 break;
4696 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004697 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004698 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004699 break;
4700
4701 case glslang::EOpLessThan:
4702 case glslang::EOpGreaterThan:
4703 case glslang::EOpLessThanEqual:
4704 case glslang::EOpGreaterThanEqual:
4705 case glslang::EOpEqual:
4706 case glslang::EOpNotEqual:
4707 case glslang::EOpVectorEqual:
4708 case glslang::EOpVectorNotEqual:
4709 comparison = true;
4710 break;
4711 default:
4712 break;
4713 }
4714
John Kessenich7c1aa102015-10-15 13:29:11 -06004715 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004716 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004717 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004718 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004719 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004720
4721 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004722 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004723 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004724
qining25262b32016-05-06 17:25:16 -04004725 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004726 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004727 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004728 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004729 }
4730
4731 if (! comparison)
4732 return 0;
4733
John Kessenich7c1aa102015-10-15 13:29:11 -06004734 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004735
John Kessenich4583b612016-08-07 19:14:22 -06004736 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004737 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4738 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004739 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004740 return result;
4741 }
John Kessenich140f3df2015-06-26 16:58:36 -06004742
4743 switch (op) {
4744 case glslang::EOpLessThan:
4745 if (isFloat)
4746 binOp = spv::OpFOrdLessThan;
4747 else if (isUnsigned)
4748 binOp = spv::OpULessThan;
4749 else
4750 binOp = spv::OpSLessThan;
4751 break;
4752 case glslang::EOpGreaterThan:
4753 if (isFloat)
4754 binOp = spv::OpFOrdGreaterThan;
4755 else if (isUnsigned)
4756 binOp = spv::OpUGreaterThan;
4757 else
4758 binOp = spv::OpSGreaterThan;
4759 break;
4760 case glslang::EOpLessThanEqual:
4761 if (isFloat)
4762 binOp = spv::OpFOrdLessThanEqual;
4763 else if (isUnsigned)
4764 binOp = spv::OpULessThanEqual;
4765 else
4766 binOp = spv::OpSLessThanEqual;
4767 break;
4768 case glslang::EOpGreaterThanEqual:
4769 if (isFloat)
4770 binOp = spv::OpFOrdGreaterThanEqual;
4771 else if (isUnsigned)
4772 binOp = spv::OpUGreaterThanEqual;
4773 else
4774 binOp = spv::OpSGreaterThanEqual;
4775 break;
4776 case glslang::EOpEqual:
4777 case glslang::EOpVectorEqual:
4778 if (isFloat)
4779 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004780 else if (isBool)
4781 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004782 else
4783 binOp = spv::OpIEqual;
4784 break;
4785 case glslang::EOpNotEqual:
4786 case glslang::EOpVectorNotEqual:
4787 if (isFloat)
4788 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004789 else if (isBool)
4790 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004791 else
4792 binOp = spv::OpINotEqual;
4793 break;
4794 default:
4795 break;
4796 }
4797
qining25262b32016-05-06 17:25:16 -04004798 if (binOp != spv::OpNop) {
4799 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004800 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004801 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004802 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004803 }
John Kessenich140f3df2015-06-26 16:58:36 -06004804
4805 return 0;
4806}
4807
John Kessenich04bb8a02015-12-12 12:28:14 -07004808//
4809// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4810// These can be any of:
4811//
4812// matrix * scalar
4813// scalar * matrix
4814// matrix * matrix linear algebraic
4815// matrix * vector
4816// vector * matrix
4817// matrix * matrix componentwise
4818// matrix op matrix op in {+, -, /}
4819// matrix op scalar op in {+, -, /}
4820// scalar op matrix op in {+, -, /}
4821//
John Kessenichead86222018-03-28 18:01:20 -06004822spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4823 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004824{
4825 bool firstClass = true;
4826
4827 // First, handle first-class matrix operations (* and matrix/scalar)
4828 switch (op) {
4829 case spv::OpFDiv:
4830 if (builder.isMatrix(left) && builder.isScalar(right)) {
4831 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004832 spv::Id resultType = builder.getTypeId(right);
4833 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004834 op = spv::OpMatrixTimesScalar;
4835 } else
4836 firstClass = false;
4837 break;
4838 case spv::OpMatrixTimesScalar:
4839 if (builder.isMatrix(right))
4840 std::swap(left, right);
4841 assert(builder.isScalar(right));
4842 break;
4843 case spv::OpVectorTimesMatrix:
4844 assert(builder.isVector(left));
4845 assert(builder.isMatrix(right));
4846 break;
4847 case spv::OpMatrixTimesVector:
4848 assert(builder.isMatrix(left));
4849 assert(builder.isVector(right));
4850 break;
4851 case spv::OpMatrixTimesMatrix:
4852 assert(builder.isMatrix(left));
4853 assert(builder.isMatrix(right));
4854 break;
4855 default:
4856 firstClass = false;
4857 break;
4858 }
4859
qining25262b32016-05-06 17:25:16 -04004860 if (firstClass) {
4861 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004862 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004863 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004864 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004865 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004866
LoopDawg592860c2016-06-09 08:57:35 -06004867 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004868 // The result type of all of them is the same type as the (a) matrix operand.
4869 // The algorithm is to:
4870 // - break the matrix(es) into vectors
4871 // - smear any scalar to a vector
4872 // - do vector operations
4873 // - make a matrix out the vector results
4874 switch (op) {
4875 case spv::OpFAdd:
4876 case spv::OpFSub:
4877 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004878 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004879 case spv::OpFMul:
4880 {
4881 // one time set up...
4882 bool leftMat = builder.isMatrix(left);
4883 bool rightMat = builder.isMatrix(right);
4884 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4885 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4886 spv::Id scalarType = builder.getScalarTypeId(typeId);
4887 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4888 std::vector<spv::Id> results;
4889 spv::Id smearVec = spv::NoResult;
4890 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004891 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004892 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004893 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004894
4895 // do each vector op
4896 for (unsigned int c = 0; c < numCols; ++c) {
4897 std::vector<unsigned int> indexes;
4898 indexes.push_back(c);
4899 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4900 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004901 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004902 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004903 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004904 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004905 }
4906
4907 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004908 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004909 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004910 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004911 }
4912 default:
4913 assert(0);
4914 return spv::NoResult;
4915 }
4916}
4917
John Kessenichead86222018-03-28 18:01:20 -06004918spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4919 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004920{
4921 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004922 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004923 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004924 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4925 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004926
4927 switch (op) {
4928 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004929 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004930 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004931 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004932 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004933 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004934 unaryOp = spv::OpSNegate;
4935 break;
4936
4937 case glslang::EOpLogicalNot:
4938 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004939 unaryOp = spv::OpLogicalNot;
4940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004941 case glslang::EOpBitwiseNot:
4942 unaryOp = spv::OpNot;
4943 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004944
John Kessenich140f3df2015-06-26 16:58:36 -06004945 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004946 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004947 break;
4948 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004949 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004950 break;
4951 case glslang::EOpTranspose:
4952 unaryOp = spv::OpTranspose;
4953 break;
4954
4955 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004956 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004957 break;
4958 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004959 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004960 break;
4961 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004962 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004963 break;
4964 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004965 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004966 break;
4967 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004968 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004969 break;
4970 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004971 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004972 break;
4973 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004974 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004975 break;
4976 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004977 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004978 break;
4979
4980 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004981 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004982 break;
4983 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004984 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004985 break;
4986 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004987 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004988 break;
4989 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004996 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004997 break;
4998
4999 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005000 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005001 break;
5002 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005003 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005004 break;
5005
5006 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005007 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005008 break;
5009 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005010 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005011 break;
5012 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005013 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005014 break;
5015 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005016 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005017 break;
5018 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005019 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005020 break;
5021 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005022 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005023 break;
5024
5025 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005026 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005027 break;
5028 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005029 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005030 break;
5031 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005032 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005033 break;
5034 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005035 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005036 break;
5037 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005038 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005039 break;
5040 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005041 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 break;
5043
5044 case glslang::EOpIsNan:
5045 unaryOp = spv::OpIsNan;
5046 break;
5047 case glslang::EOpIsInf:
5048 unaryOp = spv::OpIsInf;
5049 break;
LoopDawg592860c2016-06-09 08:57:35 -06005050 case glslang::EOpIsFinite:
5051 unaryOp = spv::OpIsFinite;
5052 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005053
Rex Xucbc426e2015-12-15 16:03:10 +08005054 case glslang::EOpFloatBitsToInt:
5055 case glslang::EOpFloatBitsToUint:
5056 case glslang::EOpIntBitsToFloat:
5057 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005058 case glslang::EOpDoubleBitsToInt64:
5059 case glslang::EOpDoubleBitsToUint64:
5060 case glslang::EOpInt64BitsToDouble:
5061 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005062 case glslang::EOpFloat16BitsToInt16:
5063 case glslang::EOpFloat16BitsToUint16:
5064 case glslang::EOpInt16BitsToFloat16:
5065 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005066 unaryOp = spv::OpBitcast;
5067 break;
5068
John Kessenich140f3df2015-06-26 16:58:36 -06005069 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005070 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005071 break;
5072 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005073 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005074 break;
5075 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005076 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005077 break;
5078 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005079 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005080 break;
5081 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005082 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005083 break;
5084 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005085 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005086 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005087 case glslang::EOpPackSnorm4x8:
5088 libCall = spv::GLSLstd450PackSnorm4x8;
5089 break;
5090 case glslang::EOpUnpackSnorm4x8:
5091 libCall = spv::GLSLstd450UnpackSnorm4x8;
5092 break;
5093 case glslang::EOpPackUnorm4x8:
5094 libCall = spv::GLSLstd450PackUnorm4x8;
5095 break;
5096 case glslang::EOpUnpackUnorm4x8:
5097 libCall = spv::GLSLstd450UnpackUnorm4x8;
5098 break;
5099 case glslang::EOpPackDouble2x32:
5100 libCall = spv::GLSLstd450PackDouble2x32;
5101 break;
5102 case glslang::EOpUnpackDouble2x32:
5103 libCall = spv::GLSLstd450UnpackDouble2x32;
5104 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005105
Rex Xu8ff43de2016-04-22 16:51:45 +08005106 case glslang::EOpPackInt2x32:
5107 case glslang::EOpUnpackInt2x32:
5108 case glslang::EOpPackUint2x32:
5109 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005110 case glslang::EOpPack16:
5111 case glslang::EOpPack32:
5112 case glslang::EOpPack64:
5113 case glslang::EOpUnpack32:
5114 case glslang::EOpUnpack16:
5115 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005116 case glslang::EOpPackInt2x16:
5117 case glslang::EOpUnpackInt2x16:
5118 case glslang::EOpPackUint2x16:
5119 case glslang::EOpUnpackUint2x16:
5120 case glslang::EOpPackInt4x16:
5121 case glslang::EOpUnpackInt4x16:
5122 case glslang::EOpPackUint4x16:
5123 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005124 case glslang::EOpPackFloat2x16:
5125 case glslang::EOpUnpackFloat2x16:
5126 unaryOp = spv::OpBitcast;
5127 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005128
John Kessenich140f3df2015-06-26 16:58:36 -06005129 case glslang::EOpDPdx:
5130 unaryOp = spv::OpDPdx;
5131 break;
5132 case glslang::EOpDPdy:
5133 unaryOp = spv::OpDPdy;
5134 break;
5135 case glslang::EOpFwidth:
5136 unaryOp = spv::OpFwidth;
5137 break;
5138 case glslang::EOpDPdxFine:
5139 unaryOp = spv::OpDPdxFine;
5140 break;
5141 case glslang::EOpDPdyFine:
5142 unaryOp = spv::OpDPdyFine;
5143 break;
5144 case glslang::EOpFwidthFine:
5145 unaryOp = spv::OpFwidthFine;
5146 break;
5147 case glslang::EOpDPdxCoarse:
5148 unaryOp = spv::OpDPdxCoarse;
5149 break;
5150 case glslang::EOpDPdyCoarse:
5151 unaryOp = spv::OpDPdyCoarse;
5152 break;
5153 case glslang::EOpFwidthCoarse:
5154 unaryOp = spv::OpFwidthCoarse;
5155 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005156 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005157#ifdef AMD_EXTENSIONS
5158 if (typeProxy == glslang::EbtFloat16)
5159 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5160#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005161 libCall = spv::GLSLstd450InterpolateAtCentroid;
5162 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005163 case glslang::EOpAny:
5164 unaryOp = spv::OpAny;
5165 break;
5166 case glslang::EOpAll:
5167 unaryOp = spv::OpAll;
5168 break;
5169
5170 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005171 if (isFloat)
5172 libCall = spv::GLSLstd450FAbs;
5173 else
5174 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005175 break;
5176 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005177 if (isFloat)
5178 libCall = spv::GLSLstd450FSign;
5179 else
5180 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005181 break;
5182
John Kessenichfc51d282015-08-19 13:34:18 -06005183 case glslang::EOpAtomicCounterIncrement:
5184 case glslang::EOpAtomicCounterDecrement:
5185 case glslang::EOpAtomicCounter:
5186 {
5187 // Handle all of the atomics in one place, in createAtomicOperation()
5188 std::vector<spv::Id> operands;
5189 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005190 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005191 }
5192
John Kessenichfc51d282015-08-19 13:34:18 -06005193 case glslang::EOpBitFieldReverse:
5194 unaryOp = spv::OpBitReverse;
5195 break;
5196 case glslang::EOpBitCount:
5197 unaryOp = spv::OpBitCount;
5198 break;
5199 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005200 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005201 break;
5202 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005203 if (isUnsigned)
5204 libCall = spv::GLSLstd450FindUMsb;
5205 else
5206 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005207 break;
5208
Rex Xu574ab042016-04-14 16:53:07 +08005209 case glslang::EOpBallot:
5210 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005211 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005212 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005213 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005214#ifdef AMD_EXTENSIONS
5215 case glslang::EOpMinInvocations:
5216 case glslang::EOpMaxInvocations:
5217 case glslang::EOpAddInvocations:
5218 case glslang::EOpMinInvocationsNonUniform:
5219 case glslang::EOpMaxInvocationsNonUniform:
5220 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005221 case glslang::EOpMinInvocationsInclusiveScan:
5222 case glslang::EOpMaxInvocationsInclusiveScan:
5223 case glslang::EOpAddInvocationsInclusiveScan:
5224 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5225 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5226 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5227 case glslang::EOpMinInvocationsExclusiveScan:
5228 case glslang::EOpMaxInvocationsExclusiveScan:
5229 case glslang::EOpAddInvocationsExclusiveScan:
5230 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5231 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5232 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005233#endif
Rex Xu51596642016-09-21 18:56:12 +08005234 {
5235 std::vector<spv::Id> operands;
5236 operands.push_back(operand);
5237 return createInvocationsOperation(op, typeId, operands, typeProxy);
5238 }
John Kessenich66011cb2018-03-06 16:12:04 -07005239 case glslang::EOpSubgroupAll:
5240 case glslang::EOpSubgroupAny:
5241 case glslang::EOpSubgroupAllEqual:
5242 case glslang::EOpSubgroupBroadcastFirst:
5243 case glslang::EOpSubgroupBallot:
5244 case glslang::EOpSubgroupInverseBallot:
5245 case glslang::EOpSubgroupBallotBitCount:
5246 case glslang::EOpSubgroupBallotInclusiveBitCount:
5247 case glslang::EOpSubgroupBallotExclusiveBitCount:
5248 case glslang::EOpSubgroupBallotFindLSB:
5249 case glslang::EOpSubgroupBallotFindMSB:
5250 case glslang::EOpSubgroupAdd:
5251 case glslang::EOpSubgroupMul:
5252 case glslang::EOpSubgroupMin:
5253 case glslang::EOpSubgroupMax:
5254 case glslang::EOpSubgroupAnd:
5255 case glslang::EOpSubgroupOr:
5256 case glslang::EOpSubgroupXor:
5257 case glslang::EOpSubgroupInclusiveAdd:
5258 case glslang::EOpSubgroupInclusiveMul:
5259 case glslang::EOpSubgroupInclusiveMin:
5260 case glslang::EOpSubgroupInclusiveMax:
5261 case glslang::EOpSubgroupInclusiveAnd:
5262 case glslang::EOpSubgroupInclusiveOr:
5263 case glslang::EOpSubgroupInclusiveXor:
5264 case glslang::EOpSubgroupExclusiveAdd:
5265 case glslang::EOpSubgroupExclusiveMul:
5266 case glslang::EOpSubgroupExclusiveMin:
5267 case glslang::EOpSubgroupExclusiveMax:
5268 case glslang::EOpSubgroupExclusiveAnd:
5269 case glslang::EOpSubgroupExclusiveOr:
5270 case glslang::EOpSubgroupExclusiveXor:
5271 case glslang::EOpSubgroupQuadSwapHorizontal:
5272 case glslang::EOpSubgroupQuadSwapVertical:
5273 case glslang::EOpSubgroupQuadSwapDiagonal: {
5274 std::vector<spv::Id> operands;
5275 operands.push_back(operand);
5276 return createSubgroupOperation(op, typeId, operands, typeProxy);
5277 }
Rex Xu9d93a232016-05-05 12:30:44 +08005278#ifdef AMD_EXTENSIONS
5279 case glslang::EOpMbcnt:
5280 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5281 libCall = spv::MbcntAMD;
5282 break;
5283
5284 case glslang::EOpCubeFaceIndex:
5285 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5286 libCall = spv::CubeFaceIndexAMD;
5287 break;
5288
5289 case glslang::EOpCubeFaceCoord:
5290 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5291 libCall = spv::CubeFaceCoordAMD;
5292 break;
5293#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005294#ifdef NV_EXTENSIONS
5295 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005296 unaryOp = spv::OpGroupNonUniformPartitionNV;
5297 break;
5298#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005299 default:
5300 return 0;
5301 }
5302
5303 spv::Id id;
5304 if (libCall >= 0) {
5305 std::vector<spv::Id> args;
5306 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005307 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005308 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005309 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005310 }
John Kessenich140f3df2015-06-26 16:58:36 -06005311
John Kessenichead86222018-03-28 18:01:20 -06005312 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005313 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005314 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005315}
5316
John Kessenich7a53f762016-01-20 11:19:27 -07005317// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005318spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5319 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005320{
5321 // Handle unary operations vector by vector.
5322 // The result type is the same type as the original type.
5323 // The algorithm is to:
5324 // - break the matrix into vectors
5325 // - apply the operation to each vector
5326 // - make a matrix out the vector results
5327
5328 // get the types sorted out
5329 int numCols = builder.getNumColumns(operand);
5330 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005331 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5332 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005333 std::vector<spv::Id> results;
5334
5335 // do each vector op
5336 for (int c = 0; c < numCols; ++c) {
5337 std::vector<unsigned int> indexes;
5338 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005339 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5340 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005341 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005342 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005343 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005344 }
5345
5346 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005347 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005348 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005349 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005350}
5351
John Kessenichad7645f2018-06-04 19:11:25 -06005352// For converting integers where both the bitwidth and the signedness could
5353// change, but only do the width change here. The caller is still responsible
5354// for the signedness conversion.
5355spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005356{
John Kessenichad7645f2018-06-04 19:11:25 -06005357 // Get the result type width, based on the type to convert to.
5358 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005359 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005360 case glslang::EOpConvInt16ToUint8:
5361 case glslang::EOpConvIntToUint8:
5362 case glslang::EOpConvInt64ToUint8:
5363 case glslang::EOpConvUint16ToInt8:
5364 case glslang::EOpConvUintToInt8:
5365 case glslang::EOpConvUint64ToInt8:
5366 width = 8;
5367 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005368 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005369 case glslang::EOpConvIntToUint16:
5370 case glslang::EOpConvInt64ToUint16:
5371 case glslang::EOpConvUint8ToInt16:
5372 case glslang::EOpConvUintToInt16:
5373 case glslang::EOpConvUint64ToInt16:
5374 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005375 break;
5376 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005377 case glslang::EOpConvInt16ToUint:
5378 case glslang::EOpConvInt64ToUint:
5379 case glslang::EOpConvUint8ToInt:
5380 case glslang::EOpConvUint16ToInt:
5381 case glslang::EOpConvUint64ToInt:
5382 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005383 break;
5384 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005385 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005386 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005387 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005388 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005389 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005390 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005391 break;
5392
5393 default:
5394 assert(false && "Default missing");
5395 break;
5396 }
5397
John Kessenichad7645f2018-06-04 19:11:25 -06005398 // Get the conversion operation and result type,
5399 // based on the target width, but the source type.
5400 spv::Id type = spv::NoType;
5401 spv::Op convOp = spv::OpNop;
5402 switch(op) {
5403 case glslang::EOpConvInt8ToUint16:
5404 case glslang::EOpConvInt8ToUint:
5405 case glslang::EOpConvInt8ToUint64:
5406 case glslang::EOpConvInt16ToUint8:
5407 case glslang::EOpConvInt16ToUint:
5408 case glslang::EOpConvInt16ToUint64:
5409 case glslang::EOpConvIntToUint8:
5410 case glslang::EOpConvIntToUint16:
5411 case glslang::EOpConvIntToUint64:
5412 case glslang::EOpConvInt64ToUint8:
5413 case glslang::EOpConvInt64ToUint16:
5414 case glslang::EOpConvInt64ToUint:
5415 convOp = spv::OpSConvert;
5416 type = builder.makeIntType(width);
5417 break;
5418 default:
5419 convOp = spv::OpUConvert;
5420 type = builder.makeUintType(width);
5421 break;
5422 }
5423
John Kessenich66011cb2018-03-06 16:12:04 -07005424 if (vectorSize > 0)
5425 type = builder.makeVectorType(type, vectorSize);
5426
John Kessenichad7645f2018-06-04 19:11:25 -06005427 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005428}
5429
John Kessenichead86222018-03-28 18:01:20 -06005430spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5431 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005432{
5433 spv::Op convOp = spv::OpNop;
5434 spv::Id zero = 0;
5435 spv::Id one = 0;
5436
5437 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5438
5439 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005440 case glslang::EOpConvInt8ToBool:
5441 case glslang::EOpConvUint8ToBool:
5442 zero = builder.makeUint8Constant(0);
5443 zero = makeSmearedConstant(zero, vectorSize);
5444 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005445 case glslang::EOpConvInt16ToBool:
5446 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005447 zero = builder.makeUint16Constant(0);
5448 zero = makeSmearedConstant(zero, vectorSize);
5449 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5450 case glslang::EOpConvIntToBool:
5451 case glslang::EOpConvUintToBool:
5452 zero = builder.makeUintConstant(0);
5453 zero = makeSmearedConstant(zero, vectorSize);
5454 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5455 case glslang::EOpConvInt64ToBool:
5456 case glslang::EOpConvUint64ToBool:
5457 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005458 zero = makeSmearedConstant(zero, vectorSize);
5459 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5460
5461 case glslang::EOpConvFloatToBool:
5462 zero = builder.makeFloatConstant(0.0F);
5463 zero = makeSmearedConstant(zero, vectorSize);
5464 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5465
5466 case glslang::EOpConvDoubleToBool:
5467 zero = builder.makeDoubleConstant(0.0);
5468 zero = makeSmearedConstant(zero, vectorSize);
5469 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5470
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005471 case glslang::EOpConvFloat16ToBool:
5472 zero = builder.makeFloat16Constant(0.0F);
5473 zero = makeSmearedConstant(zero, vectorSize);
5474 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005475
John Kessenich140f3df2015-06-26 16:58:36 -06005476 case glslang::EOpConvBoolToFloat:
5477 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005478 zero = builder.makeFloatConstant(0.0F);
5479 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005481
John Kessenich140f3df2015-06-26 16:58:36 -06005482 case glslang::EOpConvBoolToDouble:
5483 convOp = spv::OpSelect;
5484 zero = builder.makeDoubleConstant(0.0);
5485 one = builder.makeDoubleConstant(1.0);
5486 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005487
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005488 case glslang::EOpConvBoolToFloat16:
5489 convOp = spv::OpSelect;
5490 zero = builder.makeFloat16Constant(0.0F);
5491 one = builder.makeFloat16Constant(1.0F);
5492 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005493
5494 case glslang::EOpConvBoolToInt8:
5495 zero = builder.makeInt8Constant(0);
5496 one = builder.makeInt8Constant(1);
5497 convOp = spv::OpSelect;
5498 break;
5499
5500 case glslang::EOpConvBoolToUint8:
5501 zero = builder.makeUint8Constant(0);
5502 one = builder.makeUint8Constant(1);
5503 convOp = spv::OpSelect;
5504 break;
5505
5506 case glslang::EOpConvBoolToInt16:
5507 zero = builder.makeInt16Constant(0);
5508 one = builder.makeInt16Constant(1);
5509 convOp = spv::OpSelect;
5510 break;
5511
5512 case glslang::EOpConvBoolToUint16:
5513 zero = builder.makeUint16Constant(0);
5514 one = builder.makeUint16Constant(1);
5515 convOp = spv::OpSelect;
5516 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005517
John Kessenich140f3df2015-06-26 16:58:36 -06005518 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005519 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005520 if (op == glslang::EOpConvBoolToInt64)
5521 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005522 else
5523 zero = builder.makeIntConstant(0);
5524
5525 if (op == glslang::EOpConvBoolToInt64)
5526 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005527 else
5528 one = builder.makeIntConstant(1);
5529
John Kessenich140f3df2015-06-26 16:58:36 -06005530 convOp = spv::OpSelect;
5531 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005532
John Kessenich140f3df2015-06-26 16:58:36 -06005533 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005534 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005535 if (op == glslang::EOpConvBoolToUint64)
5536 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005537 else
5538 zero = builder.makeUintConstant(0);
5539
5540 if (op == glslang::EOpConvBoolToUint64)
5541 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005542 else
5543 one = builder.makeUintConstant(1);
5544
John Kessenich140f3df2015-06-26 16:58:36 -06005545 convOp = spv::OpSelect;
5546 break;
5547
John Kessenich66011cb2018-03-06 16:12:04 -07005548 case glslang::EOpConvInt8ToFloat16:
5549 case glslang::EOpConvInt8ToFloat:
5550 case glslang::EOpConvInt8ToDouble:
5551 case glslang::EOpConvInt16ToFloat16:
5552 case glslang::EOpConvInt16ToFloat:
5553 case glslang::EOpConvInt16ToDouble:
5554 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005555 case glslang::EOpConvIntToFloat:
5556 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005557 case glslang::EOpConvInt64ToFloat:
5558 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005559 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005560 convOp = spv::OpConvertSToF;
5561 break;
5562
John Kessenich66011cb2018-03-06 16:12:04 -07005563 case glslang::EOpConvUint8ToFloat16:
5564 case glslang::EOpConvUint8ToFloat:
5565 case glslang::EOpConvUint8ToDouble:
5566 case glslang::EOpConvUint16ToFloat16:
5567 case glslang::EOpConvUint16ToFloat:
5568 case glslang::EOpConvUint16ToDouble:
5569 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005570 case glslang::EOpConvUintToFloat:
5571 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005572 case glslang::EOpConvUint64ToFloat:
5573 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005574 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005575 convOp = spv::OpConvertUToF;
5576 break;
5577
5578 case glslang::EOpConvDoubleToFloat:
5579 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005580 case glslang::EOpConvDoubleToFloat16:
5581 case glslang::EOpConvFloat16ToDouble:
5582 case glslang::EOpConvFloatToFloat16:
5583 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005584 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005585 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005586 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005587 break;
5588
John Kessenich66011cb2018-03-06 16:12:04 -07005589 case glslang::EOpConvFloat16ToInt8:
5590 case glslang::EOpConvFloatToInt8:
5591 case glslang::EOpConvDoubleToInt8:
5592 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005593 case glslang::EOpConvFloatToInt16:
5594 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005595 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005596 case glslang::EOpConvFloatToInt:
5597 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005598 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005599 case glslang::EOpConvFloatToInt64:
5600 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005601 convOp = spv::OpConvertFToS;
5602 break;
5603
John Kessenich66011cb2018-03-06 16:12:04 -07005604 case glslang::EOpConvUint8ToInt8:
5605 case glslang::EOpConvInt8ToUint8:
5606 case glslang::EOpConvUint16ToInt16:
5607 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005608 case glslang::EOpConvUintToInt:
5609 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005610 case glslang::EOpConvUint64ToInt64:
5611 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005612 if (builder.isInSpecConstCodeGenMode()) {
5613 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005614 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5615 zero = builder.makeUint8Constant(0);
5616 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005617 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005618 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5619 zero = builder.makeUint64Constant(0);
5620 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005621 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005622 }
qining189b2032016-04-12 23:16:20 -04005623 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005624 // Use OpIAdd, instead of OpBitcast to do the conversion when
5625 // generating for OpSpecConstantOp instruction.
5626 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5627 }
5628 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005629 convOp = spv::OpBitcast;
5630 break;
5631
John Kessenich66011cb2018-03-06 16:12:04 -07005632 case glslang::EOpConvFloat16ToUint8:
5633 case glslang::EOpConvFloatToUint8:
5634 case glslang::EOpConvDoubleToUint8:
5635 case glslang::EOpConvFloat16ToUint16:
5636 case glslang::EOpConvFloatToUint16:
5637 case glslang::EOpConvDoubleToUint16:
5638 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005639 case glslang::EOpConvFloatToUint:
5640 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005641 case glslang::EOpConvFloatToUint64:
5642 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005643 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005644 convOp = spv::OpConvertFToU;
5645 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005646
John Kessenich66011cb2018-03-06 16:12:04 -07005647 case glslang::EOpConvInt8ToInt16:
5648 case glslang::EOpConvInt8ToInt:
5649 case glslang::EOpConvInt8ToInt64:
5650 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005651 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005652 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005653 case glslang::EOpConvIntToInt8:
5654 case glslang::EOpConvIntToInt16:
5655 case glslang::EOpConvIntToInt64:
5656 case glslang::EOpConvInt64ToInt8:
5657 case glslang::EOpConvInt64ToInt16:
5658 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005659 convOp = spv::OpSConvert;
5660 break;
5661
John Kessenich66011cb2018-03-06 16:12:04 -07005662 case glslang::EOpConvUint8ToUint16:
5663 case glslang::EOpConvUint8ToUint:
5664 case glslang::EOpConvUint8ToUint64:
5665 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005666 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005667 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005668 case glslang::EOpConvUintToUint8:
5669 case glslang::EOpConvUintToUint16:
5670 case glslang::EOpConvUintToUint64:
5671 case glslang::EOpConvUint64ToUint8:
5672 case glslang::EOpConvUint64ToUint16:
5673 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005674 convOp = spv::OpUConvert;
5675 break;
5676
John Kessenich66011cb2018-03-06 16:12:04 -07005677 case glslang::EOpConvInt8ToUint16:
5678 case glslang::EOpConvInt8ToUint:
5679 case glslang::EOpConvInt8ToUint64:
5680 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005681 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005682 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005683 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005684 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005685 case glslang::EOpConvIntToUint64:
5686 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005687 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005688 case glslang::EOpConvInt64ToUint:
5689 case glslang::EOpConvUint8ToInt16:
5690 case glslang::EOpConvUint8ToInt:
5691 case glslang::EOpConvUint8ToInt64:
5692 case glslang::EOpConvUint16ToInt8:
5693 case glslang::EOpConvUint16ToInt:
5694 case glslang::EOpConvUint16ToInt64:
5695 case glslang::EOpConvUintToInt8:
5696 case glslang::EOpConvUintToInt16:
5697 case glslang::EOpConvUintToInt64:
5698 case glslang::EOpConvUint64ToInt8:
5699 case glslang::EOpConvUint64ToInt16:
5700 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005701 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005702 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005703
5704 if (builder.isInSpecConstCodeGenMode()) {
5705 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005706 switch(op) {
5707 case glslang::EOpConvInt16ToUint8:
5708 case glslang::EOpConvIntToUint8:
5709 case glslang::EOpConvInt64ToUint8:
5710 case glslang::EOpConvUint16ToInt8:
5711 case glslang::EOpConvUintToInt8:
5712 case glslang::EOpConvUint64ToInt8:
5713 zero = builder.makeUint8Constant(0);
5714 break;
5715 case glslang::EOpConvInt8ToUint16:
5716 case glslang::EOpConvIntToUint16:
5717 case glslang::EOpConvInt64ToUint16:
5718 case glslang::EOpConvUint8ToInt16:
5719 case glslang::EOpConvUintToInt16:
5720 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005721 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005722 break;
5723 case glslang::EOpConvInt8ToUint:
5724 case glslang::EOpConvInt16ToUint:
5725 case glslang::EOpConvInt64ToUint:
5726 case glslang::EOpConvUint8ToInt:
5727 case glslang::EOpConvUint16ToInt:
5728 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005729 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005730 break;
5731 case glslang::EOpConvInt8ToUint64:
5732 case glslang::EOpConvInt16ToUint64:
5733 case glslang::EOpConvIntToUint64:
5734 case glslang::EOpConvUint8ToInt64:
5735 case glslang::EOpConvUint16ToInt64:
5736 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005737 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005738 break;
5739 default:
5740 assert(false && "Default missing");
5741 break;
5742 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005743 zero = makeSmearedConstant(zero, vectorSize);
5744 // Use OpIAdd, instead of OpBitcast to do the conversion when
5745 // generating for OpSpecConstantOp instruction.
5746 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5747 }
5748 // For normal run-time conversion instruction, use OpBitcast.
5749 convOp = spv::OpBitcast;
5750 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005751 default:
5752 break;
5753 }
5754
5755 spv::Id result = 0;
5756 if (convOp == spv::OpNop)
5757 return result;
5758
5759 if (convOp == spv::OpSelect) {
5760 zero = makeSmearedConstant(zero, vectorSize);
5761 one = makeSmearedConstant(one, vectorSize);
5762 result = builder.createTriOp(convOp, destType, operand, one, zero);
5763 } else
5764 result = builder.createUnaryOp(convOp, destType, operand);
5765
John Kessenichead86222018-03-28 18:01:20 -06005766 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005767 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005768 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005769}
5770
5771spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5772{
5773 if (vectorSize == 0)
5774 return constant;
5775
5776 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5777 std::vector<spv::Id> components;
5778 for (int c = 0; c < vectorSize; ++c)
5779 components.push_back(constant);
5780 return builder.makeCompositeConstant(vectorTypeId, components);
5781}
5782
John Kessenich426394d2015-07-23 10:22:48 -06005783// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005784spv::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 -06005785{
5786 spv::Op opCode = spv::OpNop;
5787
5788 switch (op) {
5789 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005790 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005791 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005792 opCode = spv::OpAtomicIAdd;
5793 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005794 case glslang::EOpAtomicCounterSubtract:
5795 opCode = spv::OpAtomicISub;
5796 break;
John Kessenich426394d2015-07-23 10:22:48 -06005797 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005798 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005799 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005800 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005801 break;
5802 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005803 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005804 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005805 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005806 break;
5807 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005808 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005809 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005810 opCode = spv::OpAtomicAnd;
5811 break;
5812 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005813 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005814 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005815 opCode = spv::OpAtomicOr;
5816 break;
5817 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005818 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005819 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005820 opCode = spv::OpAtomicXor;
5821 break;
5822 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005823 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005824 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005825 opCode = spv::OpAtomicExchange;
5826 break;
5827 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005828 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005829 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005830 opCode = spv::OpAtomicCompareExchange;
5831 break;
5832 case glslang::EOpAtomicCounterIncrement:
5833 opCode = spv::OpAtomicIIncrement;
5834 break;
5835 case glslang::EOpAtomicCounterDecrement:
5836 opCode = spv::OpAtomicIDecrement;
5837 break;
5838 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005839 case glslang::EOpImageAtomicLoad:
5840 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005841 opCode = spv::OpAtomicLoad;
5842 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005843 case glslang::EOpAtomicStore:
5844 case glslang::EOpImageAtomicStore:
5845 opCode = spv::OpAtomicStore;
5846 break;
John Kessenich426394d2015-07-23 10:22:48 -06005847 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005848 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005849 break;
5850 }
5851
Rex Xue8fe8b02017-09-26 15:42:56 +08005852 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5853 builder.addCapability(spv::CapabilityInt64Atomics);
5854
John Kessenich426394d2015-07-23 10:22:48 -06005855 // Sort out the operands
5856 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005857 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005858 // - compare-exchange swaps the value and comparator
5859 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005860 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005861 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5862 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5863 spv::Id scopeId;
5864 if (glslangIntermediate->usingVulkanMemoryModel()) {
5865 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5866 } else {
5867 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5868 }
5869 // semantics default to relaxed
5870 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5871 spv::Id semanticsId2 = semanticsId;
5872
5873 pointerId = operands[0];
5874 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5875 // no additional operands
5876 } else if (opCode == spv::OpAtomicCompareExchange) {
5877 compareId = operands[1];
5878 valueId = operands[2];
5879 if (operands.size() > 3) {
5880 scopeId = operands[3];
5881 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5882 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5883 }
5884 } else if (opCode == spv::OpAtomicLoad) {
5885 if (operands.size() > 1) {
5886 scopeId = operands[1];
5887 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5888 }
5889 } else {
5890 // atomic store or RMW
5891 valueId = operands[1];
5892 if (operands.size() > 2) {
5893 scopeId = operands[2];
5894 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5895 }
Rex Xu04db3f52015-09-16 11:44:02 +08005896 }
John Kessenich426394d2015-07-23 10:22:48 -06005897
Jeff Bolz36831c92018-09-05 10:11:41 -05005898 // Check for capabilities
5899 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5900 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5901 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5902 }
John Kessenich426394d2015-07-23 10:22:48 -06005903
Jeff Bolz36831c92018-09-05 10:11:41 -05005904 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5905 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5906 }
John Kessenich48d6e792017-10-06 21:21:48 -06005907
Jeff Bolz36831c92018-09-05 10:11:41 -05005908 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5909 spvAtomicOperands.push_back(pointerId);
5910 spvAtomicOperands.push_back(scopeId);
5911 spvAtomicOperands.push_back(semanticsId);
5912 if (opCode == spv::OpAtomicCompareExchange) {
5913 spvAtomicOperands.push_back(semanticsId2);
5914 spvAtomicOperands.push_back(valueId);
5915 spvAtomicOperands.push_back(compareId);
5916 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5917 spvAtomicOperands.push_back(valueId);
5918 }
John Kessenich48d6e792017-10-06 21:21:48 -06005919
Jeff Bolz36831c92018-09-05 10:11:41 -05005920 if (opCode == spv::OpAtomicStore) {
5921 builder.createNoResultOp(opCode, spvAtomicOperands);
5922 return 0;
5923 } else {
5924 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5925
5926 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5927 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5928 if (op == glslang::EOpAtomicCounterDecrement)
5929 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5930
5931 return resultId;
5932 }
John Kessenich426394d2015-07-23 10:22:48 -06005933}
5934
John Kessenich91cef522016-05-05 16:45:40 -06005935// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005936spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005937{
Corentin Walleze7061422018-08-08 15:20:15 +02005938#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005939 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5940 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005941#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005942
Rex Xu51596642016-09-21 18:56:12 +08005943 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005944 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005945 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5946
chaocf200da82016-12-20 12:44:35 -08005947 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5948 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005949 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5950 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005951 } else if (op == glslang::EOpAnyInvocation ||
5952 op == glslang::EOpAllInvocations ||
5953 op == glslang::EOpAllInvocationsEqual) {
5954 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5955 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005956 } else {
5957 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005958#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005959 if (op == glslang::EOpMinInvocationsNonUniform ||
5960 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005961 op == glslang::EOpAddInvocationsNonUniform ||
5962 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5963 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5964 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5965 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5966 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5967 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005968 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005969#endif
Rex Xu51596642016-09-21 18:56:12 +08005970
Rex Xu9d93a232016-05-05 12:30:44 +08005971#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005972 switch (op) {
5973 case glslang::EOpMinInvocations:
5974 case glslang::EOpMaxInvocations:
5975 case glslang::EOpAddInvocations:
5976 case glslang::EOpMinInvocationsNonUniform:
5977 case glslang::EOpMaxInvocationsNonUniform:
5978 case glslang::EOpAddInvocationsNonUniform:
5979 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005980 break;
5981 case glslang::EOpMinInvocationsInclusiveScan:
5982 case glslang::EOpMaxInvocationsInclusiveScan:
5983 case glslang::EOpAddInvocationsInclusiveScan:
5984 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5985 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5986 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5987 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005988 break;
5989 case glslang::EOpMinInvocationsExclusiveScan:
5990 case glslang::EOpMaxInvocationsExclusiveScan:
5991 case glslang::EOpAddInvocationsExclusiveScan:
5992 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5993 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5994 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5995 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005996 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005997 default:
5998 break;
Rex Xu430ef402016-10-14 17:22:23 +08005999 }
John Kessenich149afc32018-08-14 13:31:43 -06006000 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6001 spvGroupOperands.push_back(scope);
6002 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006003 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006004 spvGroupOperands.push_back(groupOp);
6005 }
Rex Xu9d93a232016-05-05 12:30:44 +08006006#endif
Rex Xu51596642016-09-21 18:56:12 +08006007 }
6008
John Kessenich149afc32018-08-14 13:31:43 -06006009 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6010 spv::IdImmediate op = { true, *opIt };
6011 spvGroupOperands.push_back(op);
6012 }
John Kessenich91cef522016-05-05 16:45:40 -06006013
6014 switch (op) {
6015 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006016 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006017 break;
John Kessenich91cef522016-05-05 16:45:40 -06006018 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006019 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006020 break;
John Kessenich91cef522016-05-05 16:45:40 -06006021 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006022 opCode = spv::OpSubgroupAllEqualKHR;
6023 break;
Rex Xu51596642016-09-21 18:56:12 +08006024 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006025 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006026 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006027 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006028 break;
6029 case glslang::EOpReadFirstInvocation:
6030 opCode = spv::OpSubgroupFirstInvocationKHR;
6031 break;
6032 case glslang::EOpBallot:
6033 {
6034 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6035 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6036 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6037 //
6038 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6039 //
6040 spv::Id uintType = builder.makeUintType(32);
6041 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6042 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6043
6044 std::vector<spv::Id> components;
6045 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6046 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6047
6048 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6049 return builder.createUnaryOp(spv::OpBitcast, typeId,
6050 builder.createCompositeConstruct(uvec2Type, components));
6051 }
6052
Rex Xu9d93a232016-05-05 12:30:44 +08006053#ifdef AMD_EXTENSIONS
6054 case glslang::EOpMinInvocations:
6055 case glslang::EOpMaxInvocations:
6056 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006057 case glslang::EOpMinInvocationsInclusiveScan:
6058 case glslang::EOpMaxInvocationsInclusiveScan:
6059 case glslang::EOpAddInvocationsInclusiveScan:
6060 case glslang::EOpMinInvocationsExclusiveScan:
6061 case glslang::EOpMaxInvocationsExclusiveScan:
6062 case glslang::EOpAddInvocationsExclusiveScan:
6063 if (op == glslang::EOpMinInvocations ||
6064 op == glslang::EOpMinInvocationsInclusiveScan ||
6065 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006066 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006067 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006068 else {
6069 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006070 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006071 else
Rex Xu51596642016-09-21 18:56:12 +08006072 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006073 }
Rex Xu430ef402016-10-14 17:22:23 +08006074 } else if (op == glslang::EOpMaxInvocations ||
6075 op == glslang::EOpMaxInvocationsInclusiveScan ||
6076 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006077 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006078 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006079 else {
6080 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006081 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006082 else
Rex Xu51596642016-09-21 18:56:12 +08006083 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006084 }
6085 } else {
6086 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006087 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006088 else
Rex Xu51596642016-09-21 18:56:12 +08006089 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006090 }
6091
Rex Xu2bbbe062016-08-23 15:41:05 +08006092 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006093 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006094
6095 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006096 case glslang::EOpMinInvocationsNonUniform:
6097 case glslang::EOpMaxInvocationsNonUniform:
6098 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006099 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6100 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6101 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6102 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6103 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6104 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6105 if (op == glslang::EOpMinInvocationsNonUniform ||
6106 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6107 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006108 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006109 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006110 else {
6111 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006112 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006113 else
Rex Xu51596642016-09-21 18:56:12 +08006114 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006115 }
6116 }
Rex Xu430ef402016-10-14 17:22:23 +08006117 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6118 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6119 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006120 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006121 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006122 else {
6123 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006124 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006125 else
Rex Xu51596642016-09-21 18:56:12 +08006126 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006127 }
6128 }
6129 else {
6130 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006131 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006132 else
Rex Xu51596642016-09-21 18:56:12 +08006133 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006134 }
6135
Rex Xu2bbbe062016-08-23 15:41:05 +08006136 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006137 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006138
6139 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006140#endif
John Kessenich91cef522016-05-05 16:45:40 -06006141 default:
6142 logger->missingFunctionality("invocation operation");
6143 return spv::NoResult;
6144 }
Rex Xu51596642016-09-21 18:56:12 +08006145
6146 assert(opCode != spv::OpNop);
6147 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006148}
6149
Rex Xu2bbbe062016-08-23 15:41:05 +08006150// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006151spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6152 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006153{
Rex Xub7072052016-09-26 15:53:40 +08006154#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006155 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6156 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006157 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006158 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006159 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6160 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6161 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006162#else
6163 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6164 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006165 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6166 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006167#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006168
6169 // Handle group invocation operations scalar by scalar.
6170 // The result type is the same type as the original type.
6171 // The algorithm is to:
6172 // - break the vector into scalars
6173 // - apply the operation to each scalar
6174 // - make a vector out the scalar results
6175
6176 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006177 int numComponents = builder.getNumComponents(operands[0]);
6178 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006179 std::vector<spv::Id> results;
6180
6181 // do each scalar op
6182 for (int comp = 0; comp < numComponents; ++comp) {
6183 std::vector<unsigned int> indexes;
6184 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006185 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6186 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006187 if (op == spv::OpSubgroupReadInvocationKHR) {
6188 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006189 spv::IdImmediate operand = { true, operands[1] };
6190 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006191 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006192 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6193 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006194 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006195 spv::IdImmediate operand = { true, operands[1] };
6196 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006197 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006198 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6199 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006200 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006201 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006202 spvGroupOperands.push_back(scalar);
6203 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006204
Rex Xub7072052016-09-26 15:53:40 +08006205 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006206 }
6207
6208 // put the pieces together
6209 return builder.createCompositeConstruct(typeId, results);
6210}
Rex Xu2bbbe062016-08-23 15:41:05 +08006211
John Kessenich66011cb2018-03-06 16:12:04 -07006212// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006213spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6214 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006215{
6216 // Add the required capabilities.
6217 switch (op) {
6218 case glslang::EOpSubgroupElect:
6219 builder.addCapability(spv::CapabilityGroupNonUniform);
6220 break;
6221 case glslang::EOpSubgroupAll:
6222 case glslang::EOpSubgroupAny:
6223 case glslang::EOpSubgroupAllEqual:
6224 builder.addCapability(spv::CapabilityGroupNonUniform);
6225 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6226 break;
6227 case glslang::EOpSubgroupBroadcast:
6228 case glslang::EOpSubgroupBroadcastFirst:
6229 case glslang::EOpSubgroupBallot:
6230 case glslang::EOpSubgroupInverseBallot:
6231 case glslang::EOpSubgroupBallotBitExtract:
6232 case glslang::EOpSubgroupBallotBitCount:
6233 case glslang::EOpSubgroupBallotInclusiveBitCount:
6234 case glslang::EOpSubgroupBallotExclusiveBitCount:
6235 case glslang::EOpSubgroupBallotFindLSB:
6236 case glslang::EOpSubgroupBallotFindMSB:
6237 builder.addCapability(spv::CapabilityGroupNonUniform);
6238 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6239 break;
6240 case glslang::EOpSubgroupShuffle:
6241 case glslang::EOpSubgroupShuffleXor:
6242 builder.addCapability(spv::CapabilityGroupNonUniform);
6243 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6244 break;
6245 case glslang::EOpSubgroupShuffleUp:
6246 case glslang::EOpSubgroupShuffleDown:
6247 builder.addCapability(spv::CapabilityGroupNonUniform);
6248 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6249 break;
6250 case glslang::EOpSubgroupAdd:
6251 case glslang::EOpSubgroupMul:
6252 case glslang::EOpSubgroupMin:
6253 case glslang::EOpSubgroupMax:
6254 case glslang::EOpSubgroupAnd:
6255 case glslang::EOpSubgroupOr:
6256 case glslang::EOpSubgroupXor:
6257 case glslang::EOpSubgroupInclusiveAdd:
6258 case glslang::EOpSubgroupInclusiveMul:
6259 case glslang::EOpSubgroupInclusiveMin:
6260 case glslang::EOpSubgroupInclusiveMax:
6261 case glslang::EOpSubgroupInclusiveAnd:
6262 case glslang::EOpSubgroupInclusiveOr:
6263 case glslang::EOpSubgroupInclusiveXor:
6264 case glslang::EOpSubgroupExclusiveAdd:
6265 case glslang::EOpSubgroupExclusiveMul:
6266 case glslang::EOpSubgroupExclusiveMin:
6267 case glslang::EOpSubgroupExclusiveMax:
6268 case glslang::EOpSubgroupExclusiveAnd:
6269 case glslang::EOpSubgroupExclusiveOr:
6270 case glslang::EOpSubgroupExclusiveXor:
6271 builder.addCapability(spv::CapabilityGroupNonUniform);
6272 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6273 break;
6274 case glslang::EOpSubgroupClusteredAdd:
6275 case glslang::EOpSubgroupClusteredMul:
6276 case glslang::EOpSubgroupClusteredMin:
6277 case glslang::EOpSubgroupClusteredMax:
6278 case glslang::EOpSubgroupClusteredAnd:
6279 case glslang::EOpSubgroupClusteredOr:
6280 case glslang::EOpSubgroupClusteredXor:
6281 builder.addCapability(spv::CapabilityGroupNonUniform);
6282 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6283 break;
6284 case glslang::EOpSubgroupQuadBroadcast:
6285 case glslang::EOpSubgroupQuadSwapHorizontal:
6286 case glslang::EOpSubgroupQuadSwapVertical:
6287 case glslang::EOpSubgroupQuadSwapDiagonal:
6288 builder.addCapability(spv::CapabilityGroupNonUniform);
6289 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6290 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006291#ifdef NV_EXTENSIONS
6292 case glslang::EOpSubgroupPartitionedAdd:
6293 case glslang::EOpSubgroupPartitionedMul:
6294 case glslang::EOpSubgroupPartitionedMin:
6295 case glslang::EOpSubgroupPartitionedMax:
6296 case glslang::EOpSubgroupPartitionedAnd:
6297 case glslang::EOpSubgroupPartitionedOr:
6298 case glslang::EOpSubgroupPartitionedXor:
6299 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6300 case glslang::EOpSubgroupPartitionedInclusiveMul:
6301 case glslang::EOpSubgroupPartitionedInclusiveMin:
6302 case glslang::EOpSubgroupPartitionedInclusiveMax:
6303 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6304 case glslang::EOpSubgroupPartitionedInclusiveOr:
6305 case glslang::EOpSubgroupPartitionedInclusiveXor:
6306 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6307 case glslang::EOpSubgroupPartitionedExclusiveMul:
6308 case glslang::EOpSubgroupPartitionedExclusiveMin:
6309 case glslang::EOpSubgroupPartitionedExclusiveMax:
6310 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6311 case glslang::EOpSubgroupPartitionedExclusiveOr:
6312 case glslang::EOpSubgroupPartitionedExclusiveXor:
6313 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6314 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6315 break;
6316#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006317 default: assert(0 && "Unhandled subgroup operation!");
6318 }
6319
6320 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6321 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6322 const bool isBool = typeProxy == glslang::EbtBool;
6323
6324 spv::Op opCode = spv::OpNop;
6325
6326 // Figure out which opcode to use.
6327 switch (op) {
6328 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6329 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6330 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6331 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6332 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6333 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6334 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6335 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6336 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6337 case glslang::EOpSubgroupBallotBitCount:
6338 case glslang::EOpSubgroupBallotInclusiveBitCount:
6339 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6340 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6341 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6342 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6343 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6344 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6345 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6346 case glslang::EOpSubgroupAdd:
6347 case glslang::EOpSubgroupInclusiveAdd:
6348 case glslang::EOpSubgroupExclusiveAdd:
6349 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006350#ifdef NV_EXTENSIONS
6351 case glslang::EOpSubgroupPartitionedAdd:
6352 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6353 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6354#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006355 if (isFloat) {
6356 opCode = spv::OpGroupNonUniformFAdd;
6357 } else {
6358 opCode = spv::OpGroupNonUniformIAdd;
6359 }
6360 break;
6361 case glslang::EOpSubgroupMul:
6362 case glslang::EOpSubgroupInclusiveMul:
6363 case glslang::EOpSubgroupExclusiveMul:
6364 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006365#ifdef NV_EXTENSIONS
6366 case glslang::EOpSubgroupPartitionedMul:
6367 case glslang::EOpSubgroupPartitionedInclusiveMul:
6368 case glslang::EOpSubgroupPartitionedExclusiveMul:
6369#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006370 if (isFloat) {
6371 opCode = spv::OpGroupNonUniformFMul;
6372 } else {
6373 opCode = spv::OpGroupNonUniformIMul;
6374 }
6375 break;
6376 case glslang::EOpSubgroupMin:
6377 case glslang::EOpSubgroupInclusiveMin:
6378 case glslang::EOpSubgroupExclusiveMin:
6379 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006380#ifdef NV_EXTENSIONS
6381 case glslang::EOpSubgroupPartitionedMin:
6382 case glslang::EOpSubgroupPartitionedInclusiveMin:
6383 case glslang::EOpSubgroupPartitionedExclusiveMin:
6384#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006385 if (isFloat) {
6386 opCode = spv::OpGroupNonUniformFMin;
6387 } else if (isUnsigned) {
6388 opCode = spv::OpGroupNonUniformUMin;
6389 } else {
6390 opCode = spv::OpGroupNonUniformSMin;
6391 }
6392 break;
6393 case glslang::EOpSubgroupMax:
6394 case glslang::EOpSubgroupInclusiveMax:
6395 case glslang::EOpSubgroupExclusiveMax:
6396 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006397#ifdef NV_EXTENSIONS
6398 case glslang::EOpSubgroupPartitionedMax:
6399 case glslang::EOpSubgroupPartitionedInclusiveMax:
6400 case glslang::EOpSubgroupPartitionedExclusiveMax:
6401#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006402 if (isFloat) {
6403 opCode = spv::OpGroupNonUniformFMax;
6404 } else if (isUnsigned) {
6405 opCode = spv::OpGroupNonUniformUMax;
6406 } else {
6407 opCode = spv::OpGroupNonUniformSMax;
6408 }
6409 break;
6410 case glslang::EOpSubgroupAnd:
6411 case glslang::EOpSubgroupInclusiveAnd:
6412 case glslang::EOpSubgroupExclusiveAnd:
6413 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006414#ifdef NV_EXTENSIONS
6415 case glslang::EOpSubgroupPartitionedAnd:
6416 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6417 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6418#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006419 if (isBool) {
6420 opCode = spv::OpGroupNonUniformLogicalAnd;
6421 } else {
6422 opCode = spv::OpGroupNonUniformBitwiseAnd;
6423 }
6424 break;
6425 case glslang::EOpSubgroupOr:
6426 case glslang::EOpSubgroupInclusiveOr:
6427 case glslang::EOpSubgroupExclusiveOr:
6428 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006429#ifdef NV_EXTENSIONS
6430 case glslang::EOpSubgroupPartitionedOr:
6431 case glslang::EOpSubgroupPartitionedInclusiveOr:
6432 case glslang::EOpSubgroupPartitionedExclusiveOr:
6433#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006434 if (isBool) {
6435 opCode = spv::OpGroupNonUniformLogicalOr;
6436 } else {
6437 opCode = spv::OpGroupNonUniformBitwiseOr;
6438 }
6439 break;
6440 case glslang::EOpSubgroupXor:
6441 case glslang::EOpSubgroupInclusiveXor:
6442 case glslang::EOpSubgroupExclusiveXor:
6443 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006444#ifdef NV_EXTENSIONS
6445 case glslang::EOpSubgroupPartitionedXor:
6446 case glslang::EOpSubgroupPartitionedInclusiveXor:
6447 case glslang::EOpSubgroupPartitionedExclusiveXor:
6448#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006449 if (isBool) {
6450 opCode = spv::OpGroupNonUniformLogicalXor;
6451 } else {
6452 opCode = spv::OpGroupNonUniformBitwiseXor;
6453 }
6454 break;
6455 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6456 case glslang::EOpSubgroupQuadSwapHorizontal:
6457 case glslang::EOpSubgroupQuadSwapVertical:
6458 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6459 default: assert(0 && "Unhandled subgroup operation!");
6460 }
6461
John Kessenich149afc32018-08-14 13:31:43 -06006462 // get the right Group Operation
6463 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006464 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006465 default:
6466 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006467 case glslang::EOpSubgroupBallotBitCount:
6468 case glslang::EOpSubgroupAdd:
6469 case glslang::EOpSubgroupMul:
6470 case glslang::EOpSubgroupMin:
6471 case glslang::EOpSubgroupMax:
6472 case glslang::EOpSubgroupAnd:
6473 case glslang::EOpSubgroupOr:
6474 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006475 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006476 break;
6477 case glslang::EOpSubgroupBallotInclusiveBitCount:
6478 case glslang::EOpSubgroupInclusiveAdd:
6479 case glslang::EOpSubgroupInclusiveMul:
6480 case glslang::EOpSubgroupInclusiveMin:
6481 case glslang::EOpSubgroupInclusiveMax:
6482 case glslang::EOpSubgroupInclusiveAnd:
6483 case glslang::EOpSubgroupInclusiveOr:
6484 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006485 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006486 break;
6487 case glslang::EOpSubgroupBallotExclusiveBitCount:
6488 case glslang::EOpSubgroupExclusiveAdd:
6489 case glslang::EOpSubgroupExclusiveMul:
6490 case glslang::EOpSubgroupExclusiveMin:
6491 case glslang::EOpSubgroupExclusiveMax:
6492 case glslang::EOpSubgroupExclusiveAnd:
6493 case glslang::EOpSubgroupExclusiveOr:
6494 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006495 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006496 break;
6497 case glslang::EOpSubgroupClusteredAdd:
6498 case glslang::EOpSubgroupClusteredMul:
6499 case glslang::EOpSubgroupClusteredMin:
6500 case glslang::EOpSubgroupClusteredMax:
6501 case glslang::EOpSubgroupClusteredAnd:
6502 case glslang::EOpSubgroupClusteredOr:
6503 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006504 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006505 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006506#ifdef NV_EXTENSIONS
6507 case glslang::EOpSubgroupPartitionedAdd:
6508 case glslang::EOpSubgroupPartitionedMul:
6509 case glslang::EOpSubgroupPartitionedMin:
6510 case glslang::EOpSubgroupPartitionedMax:
6511 case glslang::EOpSubgroupPartitionedAnd:
6512 case glslang::EOpSubgroupPartitionedOr:
6513 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006514 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006515 break;
6516 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6517 case glslang::EOpSubgroupPartitionedInclusiveMul:
6518 case glslang::EOpSubgroupPartitionedInclusiveMin:
6519 case glslang::EOpSubgroupPartitionedInclusiveMax:
6520 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6521 case glslang::EOpSubgroupPartitionedInclusiveOr:
6522 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006523 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006524 break;
6525 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6526 case glslang::EOpSubgroupPartitionedExclusiveMul:
6527 case glslang::EOpSubgroupPartitionedExclusiveMin:
6528 case glslang::EOpSubgroupPartitionedExclusiveMax:
6529 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6530 case glslang::EOpSubgroupPartitionedExclusiveOr:
6531 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006532 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006533 break;
6534#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006535 }
6536
John Kessenich149afc32018-08-14 13:31:43 -06006537 // build the instruction
6538 std::vector<spv::IdImmediate> spvGroupOperands;
6539
6540 // Every operation begins with the Execution Scope operand.
6541 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6542 spvGroupOperands.push_back(executionScope);
6543
6544 // Next, for all operations that use a Group Operation, push that as an operand.
6545 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006546 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006547 spvGroupOperands.push_back(groupOperand);
6548 }
6549
John Kessenich66011cb2018-03-06 16:12:04 -07006550 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006551 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6552 spv::IdImmediate operand = { true, *opIt };
6553 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006554 }
6555
6556 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006557 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006558 switch (op) {
6559 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006560 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6561 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6562 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6563 }
6564 if (directionId != spv::NoResult) {
6565 spv::IdImmediate direction = { true, directionId };
6566 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006567 }
6568
6569 return builder.createOp(opCode, typeId, spvGroupOperands);
6570}
6571
John Kessenich5e4b1242015-08-06 22:53:06 -06006572spv::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 -06006573{
John Kessenich66011cb2018-03-06 16:12:04 -07006574 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6575 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006576
John Kessenich140f3df2015-06-26 16:58:36 -06006577 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006578 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006579 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006580 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006581 spv::Id typeId0 = 0;
6582 if (consumedOperands > 0)
6583 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006584 spv::Id typeId1 = 0;
6585 if (consumedOperands > 1)
6586 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006587 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006588
6589 switch (op) {
6590 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006591 if (isFloat)
6592 libCall = spv::GLSLstd450FMin;
6593 else if (isUnsigned)
6594 libCall = spv::GLSLstd450UMin;
6595 else
6596 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006597 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006598 break;
6599 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006600 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006601 break;
6602 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006603 if (isFloat)
6604 libCall = spv::GLSLstd450FMax;
6605 else if (isUnsigned)
6606 libCall = spv::GLSLstd450UMax;
6607 else
6608 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006609 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006610 break;
6611 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006612 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006613 break;
6614 case glslang::EOpDot:
6615 opCode = spv::OpDot;
6616 break;
6617 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006618 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006619 break;
6620
6621 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006622 if (isFloat)
6623 libCall = spv::GLSLstd450FClamp;
6624 else if (isUnsigned)
6625 libCall = spv::GLSLstd450UClamp;
6626 else
6627 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006628 builder.promoteScalar(precision, operands.front(), operands[1]);
6629 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006630 break;
6631 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006632 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6633 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006634 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006635 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006636 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006637 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006638 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006639 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006640 break;
6641 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006642 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006643 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006644 break;
6645 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006646 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006647 builder.promoteScalar(precision, operands[0], operands[2]);
6648 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006649 break;
6650
6651 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006652 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006653 break;
6654 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006655 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006656 break;
6657 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006658 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006659 break;
6660 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006661 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006662 break;
6663 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006664 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006665 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006666 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006667#ifdef AMD_EXTENSIONS
6668 if (typeProxy == glslang::EbtFloat16)
6669 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6670#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006671 libCall = spv::GLSLstd450InterpolateAtSample;
6672 break;
6673 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006674#ifdef AMD_EXTENSIONS
6675 if (typeProxy == glslang::EbtFloat16)
6676 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6677#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006678 libCall = spv::GLSLstd450InterpolateAtOffset;
6679 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006680 case glslang::EOpAddCarry:
6681 opCode = spv::OpIAddCarry;
6682 typeId = builder.makeStructResultType(typeId0, typeId0);
6683 consumedOperands = 2;
6684 break;
6685 case glslang::EOpSubBorrow:
6686 opCode = spv::OpISubBorrow;
6687 typeId = builder.makeStructResultType(typeId0, typeId0);
6688 consumedOperands = 2;
6689 break;
6690 case glslang::EOpUMulExtended:
6691 opCode = spv::OpUMulExtended;
6692 typeId = builder.makeStructResultType(typeId0, typeId0);
6693 consumedOperands = 2;
6694 break;
6695 case glslang::EOpIMulExtended:
6696 opCode = spv::OpSMulExtended;
6697 typeId = builder.makeStructResultType(typeId0, typeId0);
6698 consumedOperands = 2;
6699 break;
6700 case glslang::EOpBitfieldExtract:
6701 if (isUnsigned)
6702 opCode = spv::OpBitFieldUExtract;
6703 else
6704 opCode = spv::OpBitFieldSExtract;
6705 break;
6706 case glslang::EOpBitfieldInsert:
6707 opCode = spv::OpBitFieldInsert;
6708 break;
6709
6710 case glslang::EOpFma:
6711 libCall = spv::GLSLstd450Fma;
6712 break;
6713 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006714 {
6715 libCall = spv::GLSLstd450FrexpStruct;
6716 assert(builder.isPointerType(typeId1));
6717 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006718 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006719#ifdef AMD_EXTENSIONS
6720 if (width == 16)
6721 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6722 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6723#endif
Rex Xu470026f2017-03-29 17:12:40 +08006724 if (builder.getNumComponents(operands[0]) == 1)
6725 frexpIntType = builder.makeIntegerType(width, true);
6726 else
6727 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6728 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6729 consumedOperands = 1;
6730 }
John Kessenich55e7d112015-11-15 21:33:39 -07006731 break;
6732 case glslang::EOpLdexp:
6733 libCall = spv::GLSLstd450Ldexp;
6734 break;
6735
Rex Xu574ab042016-04-14 16:53:07 +08006736 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006737 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006738
John Kessenich66011cb2018-03-06 16:12:04 -07006739 case glslang::EOpSubgroupBroadcast:
6740 case glslang::EOpSubgroupBallotBitExtract:
6741 case glslang::EOpSubgroupShuffle:
6742 case glslang::EOpSubgroupShuffleXor:
6743 case glslang::EOpSubgroupShuffleUp:
6744 case glslang::EOpSubgroupShuffleDown:
6745 case glslang::EOpSubgroupClusteredAdd:
6746 case glslang::EOpSubgroupClusteredMul:
6747 case glslang::EOpSubgroupClusteredMin:
6748 case glslang::EOpSubgroupClusteredMax:
6749 case glslang::EOpSubgroupClusteredAnd:
6750 case glslang::EOpSubgroupClusteredOr:
6751 case glslang::EOpSubgroupClusteredXor:
6752 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006753#ifdef NV_EXTENSIONS
6754 case glslang::EOpSubgroupPartitionedAdd:
6755 case glslang::EOpSubgroupPartitionedMul:
6756 case glslang::EOpSubgroupPartitionedMin:
6757 case glslang::EOpSubgroupPartitionedMax:
6758 case glslang::EOpSubgroupPartitionedAnd:
6759 case glslang::EOpSubgroupPartitionedOr:
6760 case glslang::EOpSubgroupPartitionedXor:
6761 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6762 case glslang::EOpSubgroupPartitionedInclusiveMul:
6763 case glslang::EOpSubgroupPartitionedInclusiveMin:
6764 case glslang::EOpSubgroupPartitionedInclusiveMax:
6765 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6766 case glslang::EOpSubgroupPartitionedInclusiveOr:
6767 case glslang::EOpSubgroupPartitionedInclusiveXor:
6768 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6769 case glslang::EOpSubgroupPartitionedExclusiveMul:
6770 case glslang::EOpSubgroupPartitionedExclusiveMin:
6771 case glslang::EOpSubgroupPartitionedExclusiveMax:
6772 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6773 case glslang::EOpSubgroupPartitionedExclusiveOr:
6774 case glslang::EOpSubgroupPartitionedExclusiveXor:
6775#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006776 return createSubgroupOperation(op, typeId, operands, typeProxy);
6777
Rex Xu9d93a232016-05-05 12:30:44 +08006778#ifdef AMD_EXTENSIONS
6779 case glslang::EOpSwizzleInvocations:
6780 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6781 libCall = spv::SwizzleInvocationsAMD;
6782 break;
6783 case glslang::EOpSwizzleInvocationsMasked:
6784 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6785 libCall = spv::SwizzleInvocationsMaskedAMD;
6786 break;
6787 case glslang::EOpWriteInvocation:
6788 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6789 libCall = spv::WriteInvocationAMD;
6790 break;
6791
6792 case glslang::EOpMin3:
6793 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6794 if (isFloat)
6795 libCall = spv::FMin3AMD;
6796 else {
6797 if (isUnsigned)
6798 libCall = spv::UMin3AMD;
6799 else
6800 libCall = spv::SMin3AMD;
6801 }
6802 break;
6803 case glslang::EOpMax3:
6804 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6805 if (isFloat)
6806 libCall = spv::FMax3AMD;
6807 else {
6808 if (isUnsigned)
6809 libCall = spv::UMax3AMD;
6810 else
6811 libCall = spv::SMax3AMD;
6812 }
6813 break;
6814 case glslang::EOpMid3:
6815 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6816 if (isFloat)
6817 libCall = spv::FMid3AMD;
6818 else {
6819 if (isUnsigned)
6820 libCall = spv::UMid3AMD;
6821 else
6822 libCall = spv::SMid3AMD;
6823 }
6824 break;
6825
6826 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006827 if (typeProxy == glslang::EbtFloat16)
6828 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006829 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6830 libCall = spv::InterpolateAtVertexAMD;
6831 break;
6832#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006833 case glslang::EOpBarrier:
6834 {
6835 // This is for the extended controlBarrier function, with four operands.
6836 // The unextended barrier() goes through createNoArgOperation.
6837 assert(operands.size() == 4);
6838 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6839 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6840 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6841 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6842 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6843 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6844 }
6845 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6846 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6847 }
6848 return 0;
6849 }
6850 break;
6851 case glslang::EOpMemoryBarrier:
6852 {
6853 // This is for the extended memoryBarrier function, with three operands.
6854 // The unextended memoryBarrier() goes through createNoArgOperation.
6855 assert(operands.size() == 3);
6856 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6857 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6858 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6859 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6860 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6861 }
6862 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6863 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6864 }
6865 return 0;
6866 }
6867 break;
Chao Chen3c366992018-09-19 11:41:59 -07006868
6869#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006870 case glslang::EOpReportIntersectionNV:
6871 {
6872 typeId = builder.makeBoolType();
6873 opCode = spv::OpReportIntersectionNVX;
6874 }
6875 break;
6876 case glslang::EOpTraceNV:
6877 {
6878 builder.createNoResultOp(spv::OpTraceNVX, operands);
6879 return 0;
6880 }
6881 break;
Chao Chen3c366992018-09-19 11:41:59 -07006882 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6883 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6884 return 0;
6885#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006886 default:
6887 return 0;
6888 }
6889
6890 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006891 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006892 // Use an extended instruction from the standard library.
6893 // Construct the call arguments, without modifying the original operands vector.
6894 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6895 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006896 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006897 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006898 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006899 case 0:
6900 // should all be handled by visitAggregate and createNoArgOperation
6901 assert(0);
6902 return 0;
6903 case 1:
6904 // should all be handled by createUnaryOperation
6905 assert(0);
6906 return 0;
6907 case 2:
6908 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6909 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006910 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006911 // anything 3 or over doesn't have l-value operands, so all should be consumed
6912 assert(consumedOperands == operands.size());
6913 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006914 break;
6915 }
6916 }
6917
John Kessenich55e7d112015-11-15 21:33:39 -07006918 // Decode the return types that were structures
6919 switch (op) {
6920 case glslang::EOpAddCarry:
6921 case glslang::EOpSubBorrow:
6922 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6923 id = builder.createCompositeExtract(id, typeId0, 0);
6924 break;
6925 case glslang::EOpUMulExtended:
6926 case glslang::EOpIMulExtended:
6927 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6928 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6929 break;
6930 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006931 {
6932 assert(operands.size() == 2);
6933 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6934 // "exp" is floating-point type (from HLSL intrinsic)
6935 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6936 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6937 builder.createStore(member1, operands[1]);
6938 } else
6939 // "exp" is integer type (from GLSL built-in function)
6940 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6941 id = builder.createCompositeExtract(id, typeId0, 0);
6942 }
John Kessenich55e7d112015-11-15 21:33:39 -07006943 break;
6944 default:
6945 break;
6946 }
6947
John Kessenich32cfd492016-02-02 12:37:46 -07006948 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006949}
6950
Rex Xu9d93a232016-05-05 12:30:44 +08006951// Intrinsics with no arguments (or no return value, and no precision).
6952spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006953{
Jeff Bolz36831c92018-09-05 10:11:41 -05006954 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6955 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006956
6957 switch (op) {
6958 case glslang::EOpEmitVertex:
6959 builder.createNoResultOp(spv::OpEmitVertex);
6960 return 0;
6961 case glslang::EOpEndPrimitive:
6962 builder.createNoResultOp(spv::OpEndPrimitive);
6963 return 0;
6964 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006965 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006966 if (glslangIntermediate->usingVulkanMemoryModel()) {
6967 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6968 spv::MemorySemanticsOutputMemoryKHRMask |
6969 spv::MemorySemanticsAcquireReleaseMask);
6970 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6971 } else {
6972 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6973 }
John Kessenich82979362017-12-11 04:02:24 -07006974 } else {
6975 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6976 spv::MemorySemanticsWorkgroupMemoryMask |
6977 spv::MemorySemanticsAcquireReleaseMask);
6978 }
John Kessenich140f3df2015-06-26 16:58:36 -06006979 return 0;
6980 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006981 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6982 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006983 return 0;
6984 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006985 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6986 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006987 return 0;
6988 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006989 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6990 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006991 return 0;
6992 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006993 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6994 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006995 return 0;
6996 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006997 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6998 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006999 return 0;
7000 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007001 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7002 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007003 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007004 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007005 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007006 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007007 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007008 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007009 case glslang::EOpDeviceMemoryBarrier:
7010 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7011 spv::MemorySemanticsImageMemoryMask |
7012 spv::MemorySemanticsAcquireReleaseMask);
7013 return 0;
7014 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7015 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7016 spv::MemorySemanticsImageMemoryMask |
7017 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007018 return 0;
7019 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007020 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7021 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007022 return 0;
7023 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007024 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7025 spv::MemorySemanticsWorkgroupMemoryMask |
7026 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007027 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007028 case glslang::EOpSubgroupBarrier:
7029 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7030 spv::MemorySemanticsAcquireReleaseMask);
7031 return spv::NoResult;
7032 case glslang::EOpSubgroupMemoryBarrier:
7033 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7034 spv::MemorySemanticsAcquireReleaseMask);
7035 return spv::NoResult;
7036 case glslang::EOpSubgroupMemoryBarrierBuffer:
7037 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7038 spv::MemorySemanticsAcquireReleaseMask);
7039 return spv::NoResult;
7040 case glslang::EOpSubgroupMemoryBarrierImage:
7041 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7042 spv::MemorySemanticsAcquireReleaseMask);
7043 return spv::NoResult;
7044 case glslang::EOpSubgroupMemoryBarrierShared:
7045 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7046 spv::MemorySemanticsAcquireReleaseMask);
7047 return spv::NoResult;
7048 case glslang::EOpSubgroupElect: {
7049 std::vector<spv::Id> operands;
7050 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7051 }
Rex Xu9d93a232016-05-05 12:30:44 +08007052#ifdef AMD_EXTENSIONS
7053 case glslang::EOpTime:
7054 {
7055 std::vector<spv::Id> args; // Dummy arguments
7056 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7057 return builder.setPrecision(id, precision);
7058 }
7059#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007060#ifdef NV_EXTENSIONS
7061 case glslang::EOpIgnoreIntersectionNV:
7062 builder.createNoResultOp(spv::OpIgnoreIntersectionNVX);
7063 return 0;
7064 case glslang::EOpTerminateRayNV:
7065 builder.createNoResultOp(spv::OpTerminateRayNVX);
7066 return 0;
7067#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007068 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007069 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007070 return 0;
7071 }
7072}
7073
7074spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7075{
John Kessenich2f273362015-07-18 22:34:27 -06007076 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007077 spv::Id id;
7078 if (symbolValues.end() != iter) {
7079 id = iter->second;
7080 return id;
7081 }
7082
7083 // it was not found, create it
7084 id = createSpvVariable(symbol);
7085 symbolValues[symbol->getId()] = id;
7086
Rex Xuc884b4a2016-06-29 15:03:44 +08007087 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007088 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7089 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7090 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007091#ifdef NV_EXTENSIONS
7092 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7093#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007094 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007095 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007096 if (symbol->getQualifier().hasIndex())
7097 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7098 if (symbol->getQualifier().hasComponent())
7099 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007100 // atomic counters use this:
7101 if (symbol->getQualifier().hasOffset())
7102 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007103 }
7104
scygan2c864272016-05-18 18:09:17 +02007105 if (symbol->getQualifier().hasLocation())
7106 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007107 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007108 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007109 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007110 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007111 }
John Kessenich140f3df2015-06-26 16:58:36 -06007112 if (symbol->getQualifier().hasSet())
7113 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007114 else if (IsDescriptorResource(symbol->getType())) {
7115 // default to 0
7116 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7117 }
John Kessenich140f3df2015-06-26 16:58:36 -06007118 if (symbol->getQualifier().hasBinding())
7119 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007120 if (symbol->getQualifier().hasAttachment())
7121 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007122 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007123 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007124 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007125 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007126 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007127 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007128 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7129 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7130 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7131 }
7132 if (symbol->getQualifier().hasXfbOffset())
7133 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007134 }
7135
Rex Xu1da878f2016-02-21 20:59:01 +08007136 if (symbol->getType().isImage()) {
7137 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007138 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007139 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007140 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007141 }
7142
John Kessenich140f3df2015-06-26 16:58:36 -06007143 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007144 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007145 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007146 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007147
John Kessenich5611c6d2018-04-05 11:25:02 -06007148 // nonuniform
7149 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7150
John Kessenichecba76f2017-01-06 00:34:48 -07007151#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007152 if (builtIn == spv::BuiltInSampleMask) {
7153 spv::Decoration decoration;
7154 // GL_NV_sample_mask_override_coverage extension
7155 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007156 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007157 else
7158 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007159 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007160 if (decoration != spv::DecorationMax) {
7161 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7162 }
7163 }
chaoc771d89f2017-01-13 01:10:53 -08007164 else if (builtIn == spv::BuiltInLayer) {
7165 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007166 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007167 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007168 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7169 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7170 }
John Kessenichb41bff62017-08-11 13:07:17 -06007171 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007172 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7173 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007174 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7175 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7176 }
7177 }
7178
chaoc6e5acae2016-12-20 13:28:52 -08007179 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007180 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007181 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007182 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7183 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007184 if (symbol->getQualifier().pervertexNV) {
7185 builder.addDecoration(id, spv::DecorationPerVertexNV);
7186 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7187 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7188 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007189#endif
7190
John Kessenich5d610ee2018-03-07 18:05:55 -07007191 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7192 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7193 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7194 symbol->getType().getQualifier().semanticName);
7195 }
7196
John Kessenich140f3df2015-06-26 16:58:36 -06007197 return id;
7198}
7199
Chao Chen3c366992018-09-19 11:41:59 -07007200#ifdef NV_EXTENSIONS
7201// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7202void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7203{
7204 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007205 if (qualifier.perPrimitiveNV) {
7206 // Need to add capability/extension for fragment shader.
7207 // Mesh shader already adds this by default.
7208 if (glslangIntermediate->getStage() == EShLangFragment) {
7209 builder.addCapability(spv::CapabilityMeshShadingNV);
7210 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7211 }
Chao Chen3c366992018-09-19 11:41:59 -07007212 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007213 }
Chao Chen3c366992018-09-19 11:41:59 -07007214 if (qualifier.perViewNV)
7215 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7216 if (qualifier.perTaskNV)
7217 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7218 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007219 if (qualifier.perPrimitiveNV) {
7220 // Need to add capability/extension for fragment shader.
7221 // Mesh shader already adds this by default.
7222 if (glslangIntermediate->getStage() == EShLangFragment) {
7223 builder.addCapability(spv::CapabilityMeshShadingNV);
7224 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7225 }
Chao Chen3c366992018-09-19 11:41:59 -07007226 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007227 }
Chao Chen3c366992018-09-19 11:41:59 -07007228 if (qualifier.perViewNV)
7229 builder.addDecoration(id, spv::DecorationPerViewNV);
7230 if (qualifier.perTaskNV)
7231 builder.addDecoration(id, spv::DecorationPerTaskNV);
7232 }
7233}
7234#endif
7235
John Kessenich55e7d112015-11-15 21:33:39 -07007236// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007237// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007238//
7239// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7240//
7241// Recursively walk the nodes. The nodes form a tree whose leaves are
7242// regular constants, which themselves are trees that createSpvConstant()
7243// recursively walks. So, this function walks the "top" of the tree:
7244// - emit specialization constant-building instructions for specConstant
7245// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007246spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007247{
John Kessenich7cc0e282016-03-20 00:46:02 -06007248 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007249
qining4f4bb812016-04-03 23:55:17 -04007250 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007251 if (! node.getQualifier().specConstant) {
7252 // hand off to the non-spec-constant path
7253 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7254 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007255 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007256 nextConst, false);
7257 }
7258
7259 // We now know we have a specialization constant to build
7260
John Kessenichd94c0032016-05-30 19:29:40 -06007261 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007262 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7263 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7264 std::vector<spv::Id> dimConstId;
7265 for (int dim = 0; dim < 3; ++dim) {
7266 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7267 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007268 if (specConst) {
7269 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7270 glslangIntermediate->getLocalSizeSpecId(dim));
7271 }
qining4f4bb812016-04-03 23:55:17 -04007272 }
7273 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7274 }
7275
7276 // An AST node labelled as specialization constant should be a symbol node.
7277 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7278 if (auto* sn = node.getAsSymbolNode()) {
7279 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007280 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7281 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7282 // will set the builder into spec constant op instruction generating mode.
7283 sub_tree->traverse(this);
7284 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04007285 } else if (auto* const_union_array = &sn->getConstArray()){
7286 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01007287 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
7288 builder.addName(id, sn->getName().c_str());
7289 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07007290 }
7291 }
qining4f4bb812016-04-03 23:55:17 -04007292
7293 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7294 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007295 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007296 exit(1);
7297 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007298}
7299
John Kessenich140f3df2015-06-26 16:58:36 -06007300// Use 'consts' as the flattened glslang source of scalar constants to recursively
7301// build the aggregate SPIR-V constant.
7302//
7303// If there are not enough elements present in 'consts', 0 will be substituted;
7304// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7305//
qining08408382016-03-21 09:51:37 -04007306spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007307{
7308 // vector of constants for SPIR-V
7309 std::vector<spv::Id> spvConsts;
7310
7311 // Type is used for struct and array constants
7312 spv::Id typeId = convertGlslangToSpvType(glslangType);
7313
7314 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007315 glslang::TType elementType(glslangType, 0);
7316 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007317 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007318 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007319 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007320 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007321 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007322 } else if (glslangType.getStruct()) {
7323 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7324 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007325 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007326 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007327 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7328 bool zero = nextConst >= consts.size();
7329 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007330 case glslang::EbtInt8:
7331 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7332 break;
7333 case glslang::EbtUint8:
7334 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7335 break;
7336 case glslang::EbtInt16:
7337 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7338 break;
7339 case glslang::EbtUint16:
7340 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7341 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007342 case glslang::EbtInt:
7343 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7344 break;
7345 case glslang::EbtUint:
7346 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7347 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007348 case glslang::EbtInt64:
7349 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7350 break;
7351 case glslang::EbtUint64:
7352 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7353 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007354 case glslang::EbtFloat:
7355 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7356 break;
7357 case glslang::EbtDouble:
7358 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7359 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007360 case glslang::EbtFloat16:
7361 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7362 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007363 case glslang::EbtBool:
7364 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7365 break;
7366 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007367 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007368 break;
7369 }
7370 ++nextConst;
7371 }
7372 } else {
7373 // we have a non-aggregate (scalar) constant
7374 bool zero = nextConst >= consts.size();
7375 spv::Id scalar = 0;
7376 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007377 case glslang::EbtInt8:
7378 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7379 break;
7380 case glslang::EbtUint8:
7381 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7382 break;
7383 case glslang::EbtInt16:
7384 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7385 break;
7386 case glslang::EbtUint16:
7387 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7388 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007389 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007390 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007391 break;
7392 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007393 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007394 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007395 case glslang::EbtInt64:
7396 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7397 break;
7398 case glslang::EbtUint64:
7399 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7400 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007401 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007402 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007403 break;
7404 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007405 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007406 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007407 case glslang::EbtFloat16:
7408 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7409 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007410 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007411 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007412 break;
7413 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007414 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007415 break;
7416 }
7417 ++nextConst;
7418 return scalar;
7419 }
7420
7421 return builder.makeCompositeConstant(typeId, spvConsts);
7422}
7423
John Kessenich7c1aa102015-10-15 13:29:11 -06007424// Return true if the node is a constant or symbol whose reading has no
7425// non-trivial observable cost or effect.
7426bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7427{
7428 // don't know what this is
7429 if (node == nullptr)
7430 return false;
7431
7432 // a constant is safe
7433 if (node->getAsConstantUnion() != nullptr)
7434 return true;
7435
7436 // not a symbol means non-trivial
7437 if (node->getAsSymbolNode() == nullptr)
7438 return false;
7439
7440 // a symbol, depends on what's being read
7441 switch (node->getType().getQualifier().storage) {
7442 case glslang::EvqTemporary:
7443 case glslang::EvqGlobal:
7444 case glslang::EvqIn:
7445 case glslang::EvqInOut:
7446 case glslang::EvqConst:
7447 case glslang::EvqConstReadOnly:
7448 case glslang::EvqUniform:
7449 return true;
7450 default:
7451 return false;
7452 }
qining25262b32016-05-06 17:25:16 -04007453}
John Kessenich7c1aa102015-10-15 13:29:11 -06007454
7455// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007456// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007457// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007458// Return true if trivial.
7459bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7460{
7461 if (node == nullptr)
7462 return false;
7463
John Kessenich84cc15f2017-05-24 16:44:47 -06007464 // count non scalars as trivial, as well as anything coming from HLSL
7465 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007466 return true;
7467
John Kessenich7c1aa102015-10-15 13:29:11 -06007468 // symbols and constants are trivial
7469 if (isTrivialLeaf(node))
7470 return true;
7471
7472 // otherwise, it needs to be a simple operation or one or two leaf nodes
7473
7474 // not a simple operation
7475 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7476 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7477 if (binaryNode == nullptr && unaryNode == nullptr)
7478 return false;
7479
7480 // not on leaf nodes
7481 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7482 return false;
7483
7484 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7485 return false;
7486 }
7487
7488 switch (node->getAsOperator()->getOp()) {
7489 case glslang::EOpLogicalNot:
7490 case glslang::EOpConvIntToBool:
7491 case glslang::EOpConvUintToBool:
7492 case glslang::EOpConvFloatToBool:
7493 case glslang::EOpConvDoubleToBool:
7494 case glslang::EOpEqual:
7495 case glslang::EOpNotEqual:
7496 case glslang::EOpLessThan:
7497 case glslang::EOpGreaterThan:
7498 case glslang::EOpLessThanEqual:
7499 case glslang::EOpGreaterThanEqual:
7500 case glslang::EOpIndexDirect:
7501 case glslang::EOpIndexDirectStruct:
7502 case glslang::EOpLogicalXor:
7503 case glslang::EOpAny:
7504 case glslang::EOpAll:
7505 return true;
7506 default:
7507 return false;
7508 }
7509}
7510
7511// Emit short-circuiting code, where 'right' is never evaluated unless
7512// the left side is true (for &&) or false (for ||).
7513spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7514{
7515 spv::Id boolTypeId = builder.makeBoolType();
7516
7517 // emit left operand
7518 builder.clearAccessChain();
7519 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007520 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007521
7522 // Operands to accumulate OpPhi operands
7523 std::vector<spv::Id> phiOperands;
7524 // accumulate left operand's phi information
7525 phiOperands.push_back(leftId);
7526 phiOperands.push_back(builder.getBuildPoint()->getId());
7527
7528 // Make the two kinds of operation symmetric with a "!"
7529 // || => emit "if (! left) result = right"
7530 // && => emit "if ( left) result = right"
7531 //
7532 // TODO: this runtime "not" for || could be avoided by adding functionality
7533 // to 'builder' to have an "else" without an "then"
7534 if (op == glslang::EOpLogicalOr)
7535 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7536
7537 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007538 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007539
7540 // emit right operand as the "then" part of the "if"
7541 builder.clearAccessChain();
7542 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007543 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007544
7545 // accumulate left operand's phi information
7546 phiOperands.push_back(rightId);
7547 phiOperands.push_back(builder.getBuildPoint()->getId());
7548
7549 // finish the "if"
7550 ifBuilder.makeEndIf();
7551
7552 // phi together the two results
7553 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7554}
7555
Frank Henigman541f7bb2018-01-16 00:18:26 -05007556#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007557// Return type Id of the imported set of extended instructions corresponds to the name.
7558// Import this set if it has not been imported yet.
7559spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7560{
7561 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7562 return extBuiltinMap[name];
7563 else {
Rex Xu51596642016-09-21 18:56:12 +08007564 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007565 spv::Id extBuiltins = builder.import(name);
7566 extBuiltinMap[name] = extBuiltins;
7567 return extBuiltins;
7568 }
7569}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007570#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007571
John Kessenich140f3df2015-06-26 16:58:36 -06007572}; // end anonymous namespace
7573
7574namespace glslang {
7575
John Kessenich68d78fd2015-07-12 19:28:10 -06007576void GetSpirvVersion(std::string& version)
7577{
John Kessenich9e55f632015-07-15 10:03:39 -06007578 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007579 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007580 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007581 version = buf;
7582}
7583
John Kessenicha372a3e2017-11-02 22:32:14 -06007584// For low-order part of the generator's magic number. Bump up
7585// when there is a change in the style (e.g., if SSA form changes,
7586// or a different instruction sequence to do something gets used).
7587int GetSpirvGeneratorVersion()
7588{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007589 // return 1; // start
7590 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007591 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007592 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007593 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007594 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7595 // versions 4 and 6 each generate OpArrayLength as it has long been done
7596 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007597}
7598
John Kessenich140f3df2015-06-26 16:58:36 -06007599// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007600void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007601{
7602 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007603 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007604 if (out.fail())
7605 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007606 for (int i = 0; i < (int)spirv.size(); ++i) {
7607 unsigned int word = spirv[i];
7608 out.write((const char*)&word, 4);
7609 }
7610 out.close();
7611}
7612
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007613// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007614void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007615{
7616 std::ofstream out;
7617 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007618 if (out.fail())
7619 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007620 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007621 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007622 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007623 if (varName != nullptr) {
7624 out << "\t #pragma once" << std::endl;
7625 out << "const uint32_t " << varName << "[] = {" << std::endl;
7626 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007627 const int WORDS_PER_LINE = 8;
7628 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7629 out << "\t";
7630 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7631 const unsigned int word = spirv[i + j];
7632 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7633 if (i + j + 1 < (int)spirv.size()) {
7634 out << ",";
7635 }
7636 }
7637 out << std::endl;
7638 }
Flavio15017db2017-02-15 14:29:33 -08007639 if (varName != nullptr) {
7640 out << "};";
7641 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007642 out.close();
7643}
7644
John Kessenich140f3df2015-06-26 16:58:36 -06007645//
7646// Set up the glslang traversal
7647//
John Kessenich4e11b612018-08-30 16:56:59 -06007648void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007649{
Lei Zhang17535f72016-05-04 15:55:59 -04007650 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007651 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007652}
7653
John Kessenich4e11b612018-08-30 16:56:59 -06007654void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007655 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007656{
John Kessenich140f3df2015-06-26 16:58:36 -06007657 TIntermNode* root = intermediate.getTreeRoot();
7658
7659 if (root == 0)
7660 return;
7661
John Kessenich4e11b612018-08-30 16:56:59 -06007662 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007663 if (options == nullptr)
7664 options = &defaultOptions;
7665
John Kessenich4e11b612018-08-30 16:56:59 -06007666 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007667
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007668 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007669 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007670 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007671 it.dumpSpv(spirv);
7672
GregFfb03a552018-03-29 11:49:14 -06007673#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007674 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7675 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007676 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007677 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007678
John Kessenich4e11b612018-08-30 16:56:59 -06007679 if (options->validate)
7680 SpirvToolsValidate(intermediate, spirv, logger);
7681
John Kessenich717c80a2018-08-23 15:17:10 -06007682 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007683 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007684
GregFcd1f1692017-09-21 18:40:22 -06007685#endif
7686
John Kessenich4e11b612018-08-30 16:56:59 -06007687 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007688}
7689
7690}; // end namespace glslang