blob: d1b23d889f689e9e90e0380a40a3918580e6bc2b [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 ||
557 type.getQualifier().subgroupcoherent ||
558 type.getQualifier().workgroupcoherent ||
559 type.getQualifier().queuefamilycoherent ||
560 type.getQualifier().devicecoherent ||
561 type.getQualifier().coherent;
562 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 Chenb50c02e2018-09-19 11:42:24 -0700867
868 // raytracing
869 case glslang::EbvLaunchIdNV:
870 return spv::BuiltInLaunchIdNVX;
871 case glslang::EbvLaunchSizeNV:
872 return spv::BuiltInLaunchSizeNVX;
873 case glslang::EbvWorldRayOriginNV:
874 return spv::BuiltInWorldRayOriginNVX;
875 case glslang::EbvWorldRayDirectionNV:
876 return spv::BuiltInWorldRayDirectionNVX;
877 case glslang::EbvObjectRayOriginNV:
878 return spv::BuiltInObjectRayOriginNVX;
879 case glslang::EbvObjectRayDirectionNV:
880 return spv::BuiltInObjectRayDirectionNVX;
881 case glslang::EbvRayTminNV:
882 return spv::BuiltInRayTminNVX;
883 case glslang::EbvRayTmaxNV:
884 return spv::BuiltInRayTmaxNVX;
885 case glslang::EbvInstanceCustomIndexNV:
886 return spv::BuiltInInstanceCustomIndexNVX;
887 case glslang::EbvHitTNV:
888 return spv::BuiltInHitTNVX;
889 case glslang::EbvHitKindNV:
890 return spv::BuiltInHitKindNVX;
891 case glslang::EbvObjectToWorldNV:
892 return spv::BuiltInObjectToWorldNVX;
893 case glslang::EbvWorldToObjectNV:
894 return spv::BuiltInWorldToObjectNVX;
Chao Chen9eada4b2018-09-19 11:39:56 -0700895 case glslang::EbvBaryCoordNV:
896 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
897 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
898 return spv::BuiltInBaryCoordNV;
899 case glslang::EbvBaryCoordNoPerspNV:
900 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
901 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
902 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700903 case glslang::EbvTaskCountNV:
904 return spv::BuiltInTaskCountNV;
905 case glslang::EbvPrimitiveCountNV:
906 return spv::BuiltInPrimitiveCountNV;
907 case glslang::EbvPrimitiveIndicesNV:
908 return spv::BuiltInPrimitiveIndicesNV;
909 case glslang::EbvClipDistancePerViewNV:
910 return spv::BuiltInClipDistancePerViewNV;
911 case glslang::EbvCullDistancePerViewNV:
912 return spv::BuiltInCullDistancePerViewNV;
913 case glslang::EbvLayerPerViewNV:
914 return spv::BuiltInLayerPerViewNV;
915 case glslang::EbvMeshViewCountNV:
916 return spv::BuiltInMeshViewCountNV;
917 case glslang::EbvMeshViewIndicesNV:
918 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800919#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800920 default:
921 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600922 }
923}
924
Rex Xufc618912015-09-09 16:42:49 +0800925// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700926spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800927{
928 assert(type.getBasicType() == glslang::EbtSampler);
929
John Kessenich5d0fa972016-02-15 11:57:00 -0700930 // Check for capabilities
931 switch (type.getQualifier().layoutFormat) {
932 case glslang::ElfRg32f:
933 case glslang::ElfRg16f:
934 case glslang::ElfR11fG11fB10f:
935 case glslang::ElfR16f:
936 case glslang::ElfRgba16:
937 case glslang::ElfRgb10A2:
938 case glslang::ElfRg16:
939 case glslang::ElfRg8:
940 case glslang::ElfR16:
941 case glslang::ElfR8:
942 case glslang::ElfRgba16Snorm:
943 case glslang::ElfRg16Snorm:
944 case glslang::ElfRg8Snorm:
945 case glslang::ElfR16Snorm:
946 case glslang::ElfR8Snorm:
947
948 case glslang::ElfRg32i:
949 case glslang::ElfRg16i:
950 case glslang::ElfRg8i:
951 case glslang::ElfR16i:
952 case glslang::ElfR8i:
953
954 case glslang::ElfRgb10a2ui:
955 case glslang::ElfRg32ui:
956 case glslang::ElfRg16ui:
957 case glslang::ElfRg8ui:
958 case glslang::ElfR16ui:
959 case glslang::ElfR8ui:
960 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
961 break;
962
963 default:
964 break;
965 }
966
967 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800968 switch (type.getQualifier().layoutFormat) {
969 case glslang::ElfNone: return spv::ImageFormatUnknown;
970 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
971 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
972 case glslang::ElfR32f: return spv::ImageFormatR32f;
973 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
974 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
975 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
976 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
977 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
978 case glslang::ElfR16f: return spv::ImageFormatR16f;
979 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
980 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
981 case glslang::ElfRg16: return spv::ImageFormatRg16;
982 case glslang::ElfRg8: return spv::ImageFormatRg8;
983 case glslang::ElfR16: return spv::ImageFormatR16;
984 case glslang::ElfR8: return spv::ImageFormatR8;
985 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
986 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
987 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
988 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
989 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
990 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
991 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
992 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
993 case glslang::ElfR32i: return spv::ImageFormatR32i;
994 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
995 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
996 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
997 case glslang::ElfR16i: return spv::ImageFormatR16i;
998 case glslang::ElfR8i: return spv::ImageFormatR8i;
999 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1000 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1001 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1002 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1003 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1004 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1005 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1006 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1007 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1008 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001009 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001010 }
1011}
1012
John Kesseniche18fd202018-01-30 11:01:39 -07001013spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001014{
John Kesseniche18fd202018-01-30 11:01:39 -07001015 if (selectionNode.getFlatten())
1016 return spv::SelectionControlFlattenMask;
1017 if (selectionNode.getDontFlatten())
1018 return spv::SelectionControlDontFlattenMask;
1019 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001020}
1021
John Kesseniche18fd202018-01-30 11:01:39 -07001022spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001023{
John Kesseniche18fd202018-01-30 11:01:39 -07001024 if (switchNode.getFlatten())
1025 return spv::SelectionControlFlattenMask;
1026 if (switchNode.getDontFlatten())
1027 return spv::SelectionControlDontFlattenMask;
1028 return spv::SelectionControlMaskNone;
1029}
1030
John Kessenicha2858d92018-01-31 08:11:18 -07001031// return a non-0 dependency if the dependency argument must be set
1032spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1033 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001034{
1035 spv::LoopControlMask control = spv::LoopControlMaskNone;
1036
1037 if (loopNode.getDontUnroll())
1038 control = control | spv::LoopControlDontUnrollMask;
1039 if (loopNode.getUnroll())
1040 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001041 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001042 control = control | spv::LoopControlDependencyInfiniteMask;
1043 else if (loopNode.getLoopDependency() > 0) {
1044 control = control | spv::LoopControlDependencyLengthMask;
1045 dependencyLength = loopNode.getLoopDependency();
1046 }
John Kesseniche18fd202018-01-30 11:01:39 -07001047
1048 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001049}
1050
John Kessenicha5c5fb62017-05-05 05:09:58 -06001051// Translate glslang type to SPIR-V storage class.
1052spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1053{
1054 if (type.getQualifier().isPipeInput())
1055 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001056 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001057 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001058
1059 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1060 type.getQualifier().storage == glslang::EvqUniform) {
1061 if (type.getBasicType() == glslang::EbtAtomicUint)
1062 return spv::StorageClassAtomicCounter;
1063 if (type.containsOpaque())
1064 return spv::StorageClassUniformConstant;
1065 }
1066
1067 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001068 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001069 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001070 }
1071
1072 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001073 if (type.getQualifier().layoutPushConstant)
1074 return spv::StorageClassPushConstant;
Chao Chenb50c02e2018-09-19 11:42:24 -07001075#ifdef NV_EXTENSIONS
1076 if (type.getQualifier().layoutShaderRecordNV)
1077 return spv::StorageClassShaderRecordBufferNVX;
1078#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001079 if (type.getBasicType() == glslang::EbtBlock)
1080 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001081 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001082 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001083
1084 switch (type.getQualifier().storage) {
1085 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1086 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1087 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1088 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001089#ifdef NV_EXTENSIONS
1090 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNVX;
1091 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNVX;
1092 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNVX;
1093#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001094 default:
1095 assert(0);
1096 break;
1097 }
1098
1099 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001100}
1101
John Kessenich5611c6d2018-04-05 11:25:02 -06001102// Add capabilities pertaining to how an array is indexed.
1103void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1104 const glslang::TType& indexType)
1105{
1106 if (indexType.getQualifier().isNonUniform()) {
1107 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001108 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001109 if (baseType.getBasicType() == glslang::EbtSampler) {
1110 if (baseType.getQualifier().hasAttachment())
1111 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1112 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1113 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1114 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1115 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1116 else if (baseType.isImage())
1117 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1118 else if (baseType.isTexture())
1119 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1120 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1121 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1122 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1123 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1124 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1125 }
1126 } else {
1127 // assume a dynamically uniform index
1128 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001129 if (baseType.getQualifier().hasAttachment()) {
1130 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001131 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001132 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1133 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001134 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001135 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1136 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001137 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001138 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001139 }
1140 }
1141}
1142
qining25262b32016-05-06 17:25:16 -04001143// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001144// descriptor set.
1145bool IsDescriptorResource(const glslang::TType& type)
1146{
John Kessenichf7497e22016-03-08 21:36:22 -07001147 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001148 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001149 return type.getQualifier().isUniformOrBuffer() &&
1150#ifdef NV_EXTENSIONS
1151 ! type.getQualifier().layoutShaderRecordNV &&
1152#endif
1153 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001154
1155 // non block...
1156 // basically samplerXXX/subpass/sampler/texture are all included
1157 // if they are the global-scope-class, not the function parameter
1158 // (or local, if they ever exist) class.
1159 if (type.getBasicType() == glslang::EbtSampler)
1160 return type.getQualifier().isUniformOrBuffer();
1161
1162 // None of the above.
1163 return false;
1164}
1165
John Kesseniche0b6cad2015-12-24 10:30:13 -07001166void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1167{
1168 if (child.layoutMatrix == glslang::ElmNone)
1169 child.layoutMatrix = parent.layoutMatrix;
1170
1171 if (parent.invariant)
1172 child.invariant = true;
1173 if (parent.nopersp)
1174 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001175#ifdef AMD_EXTENSIONS
1176 if (parent.explicitInterp)
1177 child.explicitInterp = true;
1178#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001179 if (parent.flat)
1180 child.flat = true;
1181 if (parent.centroid)
1182 child.centroid = true;
1183 if (parent.patch)
1184 child.patch = true;
1185 if (parent.sample)
1186 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001187 if (parent.coherent)
1188 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001189 if (parent.devicecoherent)
1190 child.devicecoherent = true;
1191 if (parent.queuefamilycoherent)
1192 child.queuefamilycoherent = true;
1193 if (parent.workgroupcoherent)
1194 child.workgroupcoherent = true;
1195 if (parent.subgroupcoherent)
1196 child.subgroupcoherent = true;
1197 if (parent.nonprivate)
1198 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001199 if (parent.volatil)
1200 child.volatil = true;
1201 if (parent.restrict)
1202 child.restrict = true;
1203 if (parent.readonly)
1204 child.readonly = true;
1205 if (parent.writeonly)
1206 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001207#ifdef NV_EXTENSIONS
1208 if (parent.perPrimitiveNV)
1209 child.perPrimitiveNV = true;
1210 if (parent.perViewNV)
1211 child.perViewNV = true;
1212 if (parent.perTaskNV)
1213 child.perTaskNV = true;
1214#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001215}
1216
John Kessenichf2b7f332016-09-01 17:05:23 -06001217bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218{
John Kessenich7b9fa252016-01-21 18:56:57 -07001219 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001220 // - struct members might inherit from a struct declaration
1221 // (note that non-block structs don't explicitly inherit,
1222 // only implicitly, meaning no decoration involved)
1223 // - affect decorations on the struct members
1224 // (note smooth does not, and expecting something like volatile
1225 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001226 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001227 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001228}
1229
John Kessenich140f3df2015-06-26 16:58:36 -06001230//
1231// Implement the TGlslangToSpvTraverser class.
1232//
1233
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001234TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001235 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1236 : TIntermTraverser(true, false, true),
1237 options(options),
1238 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001239 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001240 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001241 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001242 glslangIntermediate(glslangIntermediate)
1243{
1244 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1245
1246 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001247 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1248 glslangIntermediate->getVersion());
1249
John Kessenich121853f2017-05-31 17:11:16 -06001250 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001251 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001252 builder.setSourceFile(glslangIntermediate->getSourceFile());
1253
1254 // Set the source shader's text. If for SPV version 1.0, include
1255 // a preamble in comments stating the OpModuleProcessed instructions.
1256 // Otherwise, emit those as actual instructions.
1257 std::string text;
1258 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1259 for (int p = 0; p < (int)processes.size(); ++p) {
1260 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1261 text.append("// OpModuleProcessed ");
1262 text.append(processes[p]);
1263 text.append("\n");
1264 } else
1265 builder.addModuleProcessed(processes[p]);
1266 }
1267 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1268 text.append("#line 1\n");
1269 text.append(glslangIntermediate->getSourceText());
1270 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001271 }
John Kessenich140f3df2015-06-26 16:58:36 -06001272 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001273 if (glslangIntermediate->usingVulkanMemoryModel()) {
1274 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1275 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1276 } else {
1277 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1278 }
John Kessenicheee9d532016-09-19 18:09:30 -06001279 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1280 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001281
1282 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001283 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1284 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001285 builder.addSourceExtension(it->c_str());
1286
1287 // Add the top-level modes for this shader.
1288
John Kessenich92187592016-02-01 13:45:25 -07001289 if (glslangIntermediate->getXfbMode()) {
1290 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001291 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001292 }
John Kessenich140f3df2015-06-26 16:58:36 -06001293
1294 unsigned int mode;
1295 switch (glslangIntermediate->getStage()) {
1296 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001297 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001298 break;
1299
steve-lunarge7412492017-03-23 11:56:07 -06001300 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001301 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001302 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001303
steve-lunarge7412492017-03-23 11:56:07 -06001304 glslang::TLayoutGeometry primitive;
1305
1306 if (glslangIntermediate->getStage() == EShLangTessControl) {
1307 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1308 primitive = glslangIntermediate->getOutputPrimitive();
1309 } else {
1310 primitive = glslangIntermediate->getInputPrimitive();
1311 }
1312
1313 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001314 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1315 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1316 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001317 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001318 }
John Kessenich4016e382016-07-15 11:53:56 -06001319 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001320 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1321
John Kesseniche6903322015-10-13 16:29:02 -06001322 switch (glslangIntermediate->getVertexSpacing()) {
1323 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1324 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1325 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001326 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001327 }
John Kessenich4016e382016-07-15 11:53:56 -06001328 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001329 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1330
1331 switch (glslangIntermediate->getVertexOrder()) {
1332 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1333 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; 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 if (glslangIntermediate->getPointMode())
1340 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001341 break;
1342
1343 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001344 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001345 switch (glslangIntermediate->getInputPrimitive()) {
1346 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1347 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1348 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001349 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001350 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001351 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001352 }
John Kessenich4016e382016-07-15 11:53:56 -06001353 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001354 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001355
John Kessenich140f3df2015-06-26 16:58:36 -06001356 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1357
1358 switch (glslangIntermediate->getOutputPrimitive()) {
1359 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1360 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1361 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001362 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001363 }
John Kessenich4016e382016-07-15 11:53:56 -06001364 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001365 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1366 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1367 break;
1368
1369 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001370 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001371 if (glslangIntermediate->getPixelCenterInteger())
1372 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001373
John Kessenich140f3df2015-06-26 16:58:36 -06001374 if (glslangIntermediate->getOriginUpperLeft())
1375 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001376 else
1377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001378
1379 if (glslangIntermediate->getEarlyFragmentTests())
1380 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1381
chaocc1204522017-06-30 17:14:30 -07001382 if (glslangIntermediate->getPostDepthCoverage()) {
1383 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1384 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1385 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1386 }
1387
John Kesseniche6903322015-10-13 16:29:02 -06001388 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001389 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1390 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001391 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001392 }
John Kessenich4016e382016-07-15 11:53:56 -06001393 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001394 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1395
1396 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1397 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001398 break;
1399
1400 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001401 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001402 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1403 glslangIntermediate->getLocalSize(1),
1404 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001405#ifdef NV_EXTENSIONS
1406 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1407 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1408 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1409 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1410 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1411 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1412 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1413 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1414 }
1415#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001416 break;
1417
Chao Chen3c366992018-09-19 11:41:59 -07001418#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001419 case EShLangRayGenNV:
1420 case EShLangIntersectNV:
1421 case EShLangAnyHitNV:
1422 case EShLangClosestHitNV:
1423 case EShLangMissNV:
1424 case EShLangCallableNV:
1425 builder.addCapability(spv::CapabilityRaytracingNVX);
1426 builder.addExtension("SPV_NVX_raytracing");
1427 break;
Chao Chen3c366992018-09-19 11:41:59 -07001428 case EShLangTaskNV:
1429 case EShLangMeshNV:
1430 builder.addCapability(spv::CapabilityMeshShadingNV);
1431 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1433 glslangIntermediate->getLocalSize(1),
1434 glslangIntermediate->getLocalSize(2));
1435 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1438
1439 switch (glslangIntermediate->getOutputPrimitive()) {
1440 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1441 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1442 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1443 default: mode = spv::ExecutionModeMax; break;
1444 }
1445 if (mode != spv::ExecutionModeMax)
1446 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1447 }
1448 break;
1449#endif
1450
John Kessenich140f3df2015-06-26 16:58:36 -06001451 default:
1452 break;
1453 }
John Kessenich140f3df2015-06-26 16:58:36 -06001454}
1455
John Kessenichfca82622016-11-26 13:23:20 -07001456// Finish creating SPV, after the traversal is complete.
1457void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001458{
John Kessenichf04c51b2018-08-03 15:56:12 -06001459 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001460 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001461 builder.setBuildPoint(shaderEntry->getLastBlock());
1462 builder.leaveFunction();
1463 }
1464
John Kessenich7ba63412015-12-20 17:37:07 -07001465 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001466 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1467 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001468
John Kessenichf04c51b2018-08-03 15:56:12 -06001469 // Add capabilities, extensions, remove unneeded decorations, etc.,
1470 // based on the resulting SPIR-V.
1471 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001472}
1473
John Kessenichfca82622016-11-26 13:23:20 -07001474// Write the SPV into 'out'.
1475void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001476{
John Kessenichfca82622016-11-26 13:23:20 -07001477 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001478}
1479
1480//
1481// Implement the traversal functions.
1482//
1483// Return true from interior nodes to have the external traversal
1484// continue on to children. Return false if children were
1485// already processed.
1486//
1487
1488//
qining25262b32016-05-06 17:25:16 -04001489// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001490// - uniform/input reads
1491// - output writes
1492// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1493// - something simple that degenerates into the last bullet
1494//
1495void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1496{
qining75d1d802016-04-06 14:42:01 -04001497 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1498 if (symbol->getType().getQualifier().isSpecConstant())
1499 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1500
John Kessenich140f3df2015-06-26 16:58:36 -06001501 // getSymbolId() will set up all the IO decorations on the first call.
1502 // Formal function parameters were mapped during makeFunctions().
1503 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001504
1505 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1506 if (builder.isPointer(id)) {
1507 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001508 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1509 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1510 iOSet.insert(id);
1511 }
John Kessenich7ba63412015-12-20 17:37:07 -07001512 }
1513
1514 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001515 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001516 // Prepare to generate code for the access
1517
1518 // L-value chains will be computed left to right. We're on the symbol now,
1519 // which is the left-most part of the access chain, so now is "clear" time,
1520 // followed by setting the base.
1521 builder.clearAccessChain();
1522
1523 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001524 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001525 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001526 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001527 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001528 // These are also pure R-values.
1529 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001530 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001531 builder.setAccessChainRValue(id);
1532 else
1533 builder.setAccessChainLValue(id);
1534 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001535
1536 // Process linkage-only nodes for any special additional interface work.
1537 if (linkageOnly) {
1538 if (glslangIntermediate->getHlslFunctionality1()) {
1539 // Map implicit counter buffers to their originating buffers, which should have been
1540 // seen by now, given earlier pruning of unused counters, and preservation of order
1541 // of declaration.
1542 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1543 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1544 // Save possible originating buffers for counter buffers, keyed by
1545 // making the potential counter-buffer name.
1546 std::string keyName = symbol->getName().c_str();
1547 keyName = glslangIntermediate->addCounterBufferName(keyName);
1548 counterOriginator[keyName] = symbol;
1549 } else {
1550 // Handle a counter buffer, by finding the saved originating buffer.
1551 std::string keyName = symbol->getName().c_str();
1552 auto it = counterOriginator.find(keyName);
1553 if (it != counterOriginator.end()) {
1554 id = getSymbolId(it->second);
1555 if (id != spv::NoResult) {
1556 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001557 if (counterId != spv::NoResult) {
1558 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001559 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001560 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001561 }
1562 }
1563 }
1564 }
1565 }
1566 }
John Kessenich140f3df2015-06-26 16:58:36 -06001567}
1568
1569bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1570{
John Kesseniche485c7a2017-05-31 18:50:53 -06001571 builder.setLine(node->getLoc().line);
1572
qining40887662016-04-03 22:20:42 -04001573 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1574 if (node->getType().getQualifier().isSpecConstant())
1575 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1576
John Kessenich140f3df2015-06-26 16:58:36 -06001577 // First, handle special cases
1578 switch (node->getOp()) {
1579 case glslang::EOpAssign:
1580 case glslang::EOpAddAssign:
1581 case glslang::EOpSubAssign:
1582 case glslang::EOpMulAssign:
1583 case glslang::EOpVectorTimesMatrixAssign:
1584 case glslang::EOpVectorTimesScalarAssign:
1585 case glslang::EOpMatrixTimesScalarAssign:
1586 case glslang::EOpMatrixTimesMatrixAssign:
1587 case glslang::EOpDivAssign:
1588 case glslang::EOpModAssign:
1589 case glslang::EOpAndAssign:
1590 case glslang::EOpInclusiveOrAssign:
1591 case glslang::EOpExclusiveOrAssign:
1592 case glslang::EOpLeftShiftAssign:
1593 case glslang::EOpRightShiftAssign:
1594 // A bin-op assign "a += b" means the same thing as "a = a + b"
1595 // where a is evaluated before b. For a simple assignment, GLSL
1596 // says to evaluate the left before the right. So, always, left
1597 // node then right node.
1598 {
1599 // get the left l-value, save it away
1600 builder.clearAccessChain();
1601 node->getLeft()->traverse(this);
1602 spv::Builder::AccessChain lValue = builder.getAccessChain();
1603
1604 // evaluate the right
1605 builder.clearAccessChain();
1606 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001607 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001608
1609 if (node->getOp() != glslang::EOpAssign) {
1610 // the left is also an r-value
1611 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001612 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001613
1614 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001615 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001616 TranslateNoContractionDecoration(node->getType().getQualifier()),
1617 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001618 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001619 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1620 node->getType().getBasicType());
1621
1622 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001623 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001624 }
1625
1626 // store the result
1627 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001628 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 // assignments are expressions having an rValue after they are evaluated...
1631 builder.clearAccessChain();
1632 builder.setAccessChainRValue(rValue);
1633 }
1634 return false;
1635 case glslang::EOpIndexDirect:
1636 case glslang::EOpIndexDirectStruct:
1637 {
1638 // Get the left part of the access chain.
1639 node->getLeft()->traverse(this);
1640
1641 // Add the next element in the chain
1642
David Netoa901ffe2016-06-08 14:11:40 +01001643 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001644 if (! node->getLeft()->getType().isArray() &&
1645 node->getLeft()->getType().isVector() &&
1646 node->getOp() == glslang::EOpIndexDirect) {
1647 // This is essentially a hard-coded vector swizzle of size 1,
1648 // so short circuit the access-chain stuff with a swizzle.
1649 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001650 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001651 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001652 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001653 int spvIndex = glslangIndex;
1654 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1655 node->getOp() == glslang::EOpIndexDirectStruct)
1656 {
1657 // This may be, e.g., an anonymous block-member selection, which generally need
1658 // index remapping due to hidden members in anonymous blocks.
1659 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1660 assert(remapper.size() > 0);
1661 spvIndex = remapper[glslangIndex];
1662 }
John Kessenichebb50532016-05-16 19:22:05 -06001663
David Netoa901ffe2016-06-08 14:11:40 +01001664 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001665 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001666
1667 // Add capabilities here for accessing PointSize and clip/cull distance.
1668 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001669 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001670 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001671 }
1672 }
1673 return false;
1674 case glslang::EOpIndexIndirect:
1675 {
1676 // Structure or array or vector indirection.
1677 // Will use native SPIR-V access-chain for struct and array indirection;
1678 // matrices are arrays of vectors, so will also work for a matrix.
1679 // Will use the access chain's 'component' for variable index into a vector.
1680
1681 // This adapter is building access chains left to right.
1682 // Set up the access chain to the left.
1683 node->getLeft()->traverse(this);
1684
1685 // save it so that computing the right side doesn't trash it
1686 spv::Builder::AccessChain partial = builder.getAccessChain();
1687
1688 // compute the next index in the chain
1689 builder.clearAccessChain();
1690 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001691 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001692
John Kessenich5611c6d2018-04-05 11:25:02 -06001693 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1694
John Kessenich140f3df2015-06-26 16:58:36 -06001695 // restore the saved access chain
1696 builder.setAccessChain(partial);
1697
1698 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001699 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001700 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001701 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001702 }
1703 return false;
1704 case glslang::EOpVectorSwizzle:
1705 {
1706 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001707 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001708 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001709 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001710 }
1711 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001712 case glslang::EOpMatrixSwizzle:
1713 logger->missingFunctionality("matrix swizzle");
1714 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001715 case glslang::EOpLogicalOr:
1716 case glslang::EOpLogicalAnd:
1717 {
1718
1719 // These may require short circuiting, but can sometimes be done as straight
1720 // binary operations. The right operand must be short circuited if it has
1721 // side effects, and should probably be if it is complex.
1722 if (isTrivial(node->getRight()->getAsTyped()))
1723 break; // handle below as a normal binary operation
1724 // otherwise, we need to do dynamic short circuiting on the right operand
1725 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1726 builder.clearAccessChain();
1727 builder.setAccessChainRValue(result);
1728 }
1729 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001730 default:
1731 break;
1732 }
1733
1734 // Assume generic binary op...
1735
John Kessenich32cfd492016-02-02 12:37:46 -07001736 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001737 builder.clearAccessChain();
1738 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001739 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001740
John Kessenich32cfd492016-02-02 12:37:46 -07001741 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001742 builder.clearAccessChain();
1743 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001744 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001745
John Kessenich32cfd492016-02-02 12:37:46 -07001746 // get result
John Kessenichead86222018-03-28 18:01:20 -06001747 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001748 TranslateNoContractionDecoration(node->getType().getQualifier()),
1749 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001750 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001751 convertGlslangToSpvType(node->getType()), left, right,
1752 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001753
John Kessenich50e57562015-12-21 21:21:11 -07001754 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001755 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001756 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001757 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001758 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001759 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001760 return false;
1761 }
John Kessenich140f3df2015-06-26 16:58:36 -06001762}
1763
1764bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1765{
John Kesseniche485c7a2017-05-31 18:50:53 -06001766 builder.setLine(node->getLoc().line);
1767
qining40887662016-04-03 22:20:42 -04001768 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1769 if (node->getType().getQualifier().isSpecConstant())
1770 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1771
John Kessenichfc51d282015-08-19 13:34:18 -06001772 spv::Id result = spv::NoResult;
1773
1774 // try texturing first
1775 result = createImageTextureFunctionCall(node);
1776 if (result != spv::NoResult) {
1777 builder.clearAccessChain();
1778 builder.setAccessChainRValue(result);
1779
1780 return false; // done with this node
1781 }
1782
1783 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001784
1785 if (node->getOp() == glslang::EOpArrayLength) {
1786 // Quite special; won't want to evaluate the operand.
1787
John Kessenich5611c6d2018-04-05 11:25:02 -06001788 // Currently, the front-end does not allow .length() on an array until it is sized,
1789 // except for the last block membeor of an SSBO.
1790 // TODO: If this changes, link-time sized arrays might show up here, and need their
1791 // size extracted.
1792
John Kessenichc9a80832015-09-12 12:17:44 -06001793 // Normal .length() would have been constant folded by the front-end.
1794 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001795 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001796
John Kessenichc9a80832015-09-12 12:17:44 -06001797 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1798 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001799 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1800 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001801
1802 builder.clearAccessChain();
1803 builder.setAccessChainRValue(length);
1804
1805 return false;
1806 }
1807
John Kessenichfc51d282015-08-19 13:34:18 -06001808 // Start by evaluating the operand
1809
John Kessenich8c8505c2016-07-26 12:50:38 -06001810 // Does it need a swizzle inversion? If so, evaluation is inverted;
1811 // operate first on the swizzle base, then apply the swizzle.
1812 spv::Id invertedType = spv::NoType;
1813 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1814 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1815 invertedType = getInvertedSwizzleType(*node->getOperand());
1816
John Kessenich140f3df2015-06-26 16:58:36 -06001817 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001818 if (invertedType != spv::NoType)
1819 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1820 else
1821 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001822
Rex Xufc618912015-09-09 16:42:49 +08001823 spv::Id operand = spv::NoResult;
1824
1825 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1826 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001827 node->getOp() == glslang::EOpAtomicCounter ||
1828 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001829 operand = builder.accessChainGetLValue(); // Special case l-value operands
1830 else
John Kessenich32cfd492016-02-02 12:37:46 -07001831 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001832
John Kessenichead86222018-03-28 18:01:20 -06001833 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001834 TranslateNoContractionDecoration(node->getType().getQualifier()),
1835 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001836
1837 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001838 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001839 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
1841 // if not, then possibly an operation
1842 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001843 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001846 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001847 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001848 builder.addDecoration(result, decorations.nonUniform);
1849 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001850
John Kessenich140f3df2015-06-26 16:58:36 -06001851 builder.clearAccessChain();
1852 builder.setAccessChainRValue(result);
1853
1854 return false; // done with this node
1855 }
1856
1857 // it must be a special case, check...
1858 switch (node->getOp()) {
1859 case glslang::EOpPostIncrement:
1860 case glslang::EOpPostDecrement:
1861 case glslang::EOpPreIncrement:
1862 case glslang::EOpPreDecrement:
1863 {
1864 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001865 spv::Id one = 0;
1866 if (node->getBasicType() == glslang::EbtFloat)
1867 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001868 else if (node->getBasicType() == glslang::EbtDouble)
1869 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001870 else if (node->getBasicType() == glslang::EbtFloat16)
1871 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001872 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1873 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001874 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1875 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001876 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1877 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001878 else
1879 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001880 glslang::TOperator op;
1881 if (node->getOp() == glslang::EOpPreIncrement ||
1882 node->getOp() == glslang::EOpPostIncrement)
1883 op = glslang::EOpAdd;
1884 else
1885 op = glslang::EOpSub;
1886
John Kessenichead86222018-03-28 18:01:20 -06001887 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001888 convertGlslangToSpvType(node->getType()), operand, one,
1889 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001890 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001891
1892 // The result of operation is always stored, but conditionally the
1893 // consumed result. The consumed result is always an r-value.
1894 builder.accessChainStore(result);
1895 builder.clearAccessChain();
1896 if (node->getOp() == glslang::EOpPreIncrement ||
1897 node->getOp() == glslang::EOpPreDecrement)
1898 builder.setAccessChainRValue(result);
1899 else
1900 builder.setAccessChainRValue(operand);
1901 }
1902
1903 return false;
1904
1905 case glslang::EOpEmitStreamVertex:
1906 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1907 return false;
1908 case glslang::EOpEndStreamPrimitive:
1909 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1910 return false;
1911
1912 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001913 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001914 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001915 }
John Kessenich140f3df2015-06-26 16:58:36 -06001916}
1917
1918bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1919{
qining27e04a02016-04-14 16:40:20 -04001920 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1921 if (node->getType().getQualifier().isSpecConstant())
1922 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1923
John Kessenichfc51d282015-08-19 13:34:18 -06001924 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001925 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1926 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001927
1928 // try texturing
1929 result = createImageTextureFunctionCall(node);
1930 if (result != spv::NoResult) {
1931 builder.clearAccessChain();
1932 builder.setAccessChainRValue(result);
1933
1934 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001935 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001936#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001937 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001938#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001939 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001940 // "imageStore" is a special case, which has no result
1941 return false;
1942 }
John Kessenichfc51d282015-08-19 13:34:18 -06001943
John Kessenich140f3df2015-06-26 16:58:36 -06001944 glslang::TOperator binOp = glslang::EOpNull;
1945 bool reduceComparison = true;
1946 bool isMatrix = false;
1947 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001948 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001949
1950 assert(node->getOp());
1951
John Kessenichf6640762016-08-01 19:44:00 -06001952 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001953
1954 switch (node->getOp()) {
1955 case glslang::EOpSequence:
1956 {
1957 if (preVisit)
1958 ++sequenceDepth;
1959 else
1960 --sequenceDepth;
1961
1962 if (sequenceDepth == 1) {
1963 // If this is the parent node of all the functions, we want to see them
1964 // early, so all call points have actual SPIR-V functions to reference.
1965 // In all cases, still let the traverser visit the children for us.
1966 makeFunctions(node->getAsAggregate()->getSequence());
1967
John Kessenich6fccb3c2016-09-19 16:01:41 -06001968 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001969 // anything else gets there, so visit out of order, doing them all now.
1970 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1971
John Kessenich6a60c2f2016-12-08 21:01:59 -07001972 // 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 -06001973 // so do them manually.
1974 visitFunctions(node->getAsAggregate()->getSequence());
1975
1976 return false;
1977 }
1978
1979 return true;
1980 }
1981 case glslang::EOpLinkerObjects:
1982 {
1983 if (visit == glslang::EvPreVisit)
1984 linkageOnly = true;
1985 else
1986 linkageOnly = false;
1987
1988 return true;
1989 }
1990 case glslang::EOpComma:
1991 {
1992 // processing from left to right naturally leaves the right-most
1993 // lying around in the access chain
1994 glslang::TIntermSequence& glslangOperands = node->getSequence();
1995 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1996 glslangOperands[i]->traverse(this);
1997
1998 return false;
1999 }
2000 case glslang::EOpFunction:
2001 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002002 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002003 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002004 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002005 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002006 } else {
2007 handleFunctionEntry(node);
2008 }
2009 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002010 if (inEntryPoint)
2011 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002012 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002013 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002014 }
2015
2016 return true;
2017 case glslang::EOpParameters:
2018 // Parameters will have been consumed by EOpFunction processing, but not
2019 // the body, so we still visited the function node's children, making this
2020 // child redundant.
2021 return false;
2022 case glslang::EOpFunctionCall:
2023 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002024 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002025 if (node->isUserDefined())
2026 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002027 // 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 -07002028 if (result) {
2029 builder.clearAccessChain();
2030 builder.setAccessChainRValue(result);
2031 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002032 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002033
2034 return false;
2035 }
2036 case glslang::EOpConstructMat2x2:
2037 case glslang::EOpConstructMat2x3:
2038 case glslang::EOpConstructMat2x4:
2039 case glslang::EOpConstructMat3x2:
2040 case glslang::EOpConstructMat3x3:
2041 case glslang::EOpConstructMat3x4:
2042 case glslang::EOpConstructMat4x2:
2043 case glslang::EOpConstructMat4x3:
2044 case glslang::EOpConstructMat4x4:
2045 case glslang::EOpConstructDMat2x2:
2046 case glslang::EOpConstructDMat2x3:
2047 case glslang::EOpConstructDMat2x4:
2048 case glslang::EOpConstructDMat3x2:
2049 case glslang::EOpConstructDMat3x3:
2050 case glslang::EOpConstructDMat3x4:
2051 case glslang::EOpConstructDMat4x2:
2052 case glslang::EOpConstructDMat4x3:
2053 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002054 case glslang::EOpConstructIMat2x2:
2055 case glslang::EOpConstructIMat2x3:
2056 case glslang::EOpConstructIMat2x4:
2057 case glslang::EOpConstructIMat3x2:
2058 case glslang::EOpConstructIMat3x3:
2059 case glslang::EOpConstructIMat3x4:
2060 case glslang::EOpConstructIMat4x2:
2061 case glslang::EOpConstructIMat4x3:
2062 case glslang::EOpConstructIMat4x4:
2063 case glslang::EOpConstructUMat2x2:
2064 case glslang::EOpConstructUMat2x3:
2065 case glslang::EOpConstructUMat2x4:
2066 case glslang::EOpConstructUMat3x2:
2067 case glslang::EOpConstructUMat3x3:
2068 case glslang::EOpConstructUMat3x4:
2069 case glslang::EOpConstructUMat4x2:
2070 case glslang::EOpConstructUMat4x3:
2071 case glslang::EOpConstructUMat4x4:
2072 case glslang::EOpConstructBMat2x2:
2073 case glslang::EOpConstructBMat2x3:
2074 case glslang::EOpConstructBMat2x4:
2075 case glslang::EOpConstructBMat3x2:
2076 case glslang::EOpConstructBMat3x3:
2077 case glslang::EOpConstructBMat3x4:
2078 case glslang::EOpConstructBMat4x2:
2079 case glslang::EOpConstructBMat4x3:
2080 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002081 case glslang::EOpConstructF16Mat2x2:
2082 case glslang::EOpConstructF16Mat2x3:
2083 case glslang::EOpConstructF16Mat2x4:
2084 case glslang::EOpConstructF16Mat3x2:
2085 case glslang::EOpConstructF16Mat3x3:
2086 case glslang::EOpConstructF16Mat3x4:
2087 case glslang::EOpConstructF16Mat4x2:
2088 case glslang::EOpConstructF16Mat4x3:
2089 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002090 isMatrix = true;
2091 // fall through
2092 case glslang::EOpConstructFloat:
2093 case glslang::EOpConstructVec2:
2094 case glslang::EOpConstructVec3:
2095 case glslang::EOpConstructVec4:
2096 case glslang::EOpConstructDouble:
2097 case glslang::EOpConstructDVec2:
2098 case glslang::EOpConstructDVec3:
2099 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002100 case glslang::EOpConstructFloat16:
2101 case glslang::EOpConstructF16Vec2:
2102 case glslang::EOpConstructF16Vec3:
2103 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002104 case glslang::EOpConstructBool:
2105 case glslang::EOpConstructBVec2:
2106 case glslang::EOpConstructBVec3:
2107 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002108 case glslang::EOpConstructInt8:
2109 case glslang::EOpConstructI8Vec2:
2110 case glslang::EOpConstructI8Vec3:
2111 case glslang::EOpConstructI8Vec4:
2112 case glslang::EOpConstructUint8:
2113 case glslang::EOpConstructU8Vec2:
2114 case glslang::EOpConstructU8Vec3:
2115 case glslang::EOpConstructU8Vec4:
2116 case glslang::EOpConstructInt16:
2117 case glslang::EOpConstructI16Vec2:
2118 case glslang::EOpConstructI16Vec3:
2119 case glslang::EOpConstructI16Vec4:
2120 case glslang::EOpConstructUint16:
2121 case glslang::EOpConstructU16Vec2:
2122 case glslang::EOpConstructU16Vec3:
2123 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002124 case glslang::EOpConstructInt:
2125 case glslang::EOpConstructIVec2:
2126 case glslang::EOpConstructIVec3:
2127 case glslang::EOpConstructIVec4:
2128 case glslang::EOpConstructUint:
2129 case glslang::EOpConstructUVec2:
2130 case glslang::EOpConstructUVec3:
2131 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002132 case glslang::EOpConstructInt64:
2133 case glslang::EOpConstructI64Vec2:
2134 case glslang::EOpConstructI64Vec3:
2135 case glslang::EOpConstructI64Vec4:
2136 case glslang::EOpConstructUint64:
2137 case glslang::EOpConstructU64Vec2:
2138 case glslang::EOpConstructU64Vec3:
2139 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002140 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002141 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002142 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002143 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002144 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002145 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002146 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002147 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002148 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002149 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002150 std::vector<spv::Id> constituents;
2151 for (int c = 0; c < (int)arguments.size(); ++c)
2152 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002153 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002154 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002155 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002156 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002157 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002158
2159 builder.clearAccessChain();
2160 builder.setAccessChainRValue(constructed);
2161
2162 return false;
2163 }
2164
2165 // These six are component-wise compares with component-wise results.
2166 // Forward on to createBinaryOperation(), requesting a vector result.
2167 case glslang::EOpLessThan:
2168 case glslang::EOpGreaterThan:
2169 case glslang::EOpLessThanEqual:
2170 case glslang::EOpGreaterThanEqual:
2171 case glslang::EOpVectorEqual:
2172 case glslang::EOpVectorNotEqual:
2173 {
2174 // Map the operation to a binary
2175 binOp = node->getOp();
2176 reduceComparison = false;
2177 switch (node->getOp()) {
2178 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2179 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2180 default: binOp = node->getOp(); break;
2181 }
2182
2183 break;
2184 }
2185 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002186 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002187 binOp = glslang::EOpMul;
2188 break;
2189 case glslang::EOpOuterProduct:
2190 // two vectors multiplied to make a matrix
2191 binOp = glslang::EOpOuterProduct;
2192 break;
2193 case glslang::EOpDot:
2194 {
qining25262b32016-05-06 17:25:16 -04002195 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002196 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002197 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002198 binOp = glslang::EOpMul;
2199 break;
2200 }
2201 case glslang::EOpMod:
2202 // when an aggregate, this is the floating-point mod built-in function,
2203 // which can be emitted by the one in createBinaryOperation()
2204 binOp = glslang::EOpMod;
2205 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002206 case glslang::EOpEmitVertex:
2207 case glslang::EOpEndPrimitive:
2208 case glslang::EOpBarrier:
2209 case glslang::EOpMemoryBarrier:
2210 case glslang::EOpMemoryBarrierAtomicCounter:
2211 case glslang::EOpMemoryBarrierBuffer:
2212 case glslang::EOpMemoryBarrierImage:
2213 case glslang::EOpMemoryBarrierShared:
2214 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002215 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002216 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002217 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002218 case glslang::EOpWorkgroupMemoryBarrier:
2219 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002220 case glslang::EOpSubgroupBarrier:
2221 case glslang::EOpSubgroupMemoryBarrier:
2222 case glslang::EOpSubgroupMemoryBarrierBuffer:
2223 case glslang::EOpSubgroupMemoryBarrierImage:
2224 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002225 noReturnValue = true;
2226 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2227 break;
2228
Jeff Bolz36831c92018-09-05 10:11:41 -05002229 case glslang::EOpAtomicStore:
2230 noReturnValue = true;
2231 // fallthrough
2232 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002233 case glslang::EOpAtomicAdd:
2234 case glslang::EOpAtomicMin:
2235 case glslang::EOpAtomicMax:
2236 case glslang::EOpAtomicAnd:
2237 case glslang::EOpAtomicOr:
2238 case glslang::EOpAtomicXor:
2239 case glslang::EOpAtomicExchange:
2240 case glslang::EOpAtomicCompSwap:
2241 atomic = true;
2242 break;
2243
John Kessenich0d0c6d32017-07-23 16:08:26 -06002244 case glslang::EOpAtomicCounterAdd:
2245 case glslang::EOpAtomicCounterSubtract:
2246 case glslang::EOpAtomicCounterMin:
2247 case glslang::EOpAtomicCounterMax:
2248 case glslang::EOpAtomicCounterAnd:
2249 case glslang::EOpAtomicCounterOr:
2250 case glslang::EOpAtomicCounterXor:
2251 case glslang::EOpAtomicCounterExchange:
2252 case glslang::EOpAtomicCounterCompSwap:
2253 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2254 builder.addCapability(spv::CapabilityAtomicStorageOps);
2255 atomic = true;
2256 break;
2257
Chao Chen3c366992018-09-19 11:41:59 -07002258#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002259 case glslang::EOpIgnoreIntersectionNV:
2260 case glslang::EOpTerminateRayNV:
2261 case glslang::EOpTraceNV:
Chao Chen3c366992018-09-19 11:41:59 -07002262 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2263 noReturnValue = true;
2264 break;
2265#endif
2266
John Kessenich140f3df2015-06-26 16:58:36 -06002267 default:
2268 break;
2269 }
2270
2271 //
2272 // See if it maps to a regular operation.
2273 //
John Kessenich140f3df2015-06-26 16:58:36 -06002274 if (binOp != glslang::EOpNull) {
2275 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2276 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2277 assert(left && right);
2278
2279 builder.clearAccessChain();
2280 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002281 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002282
2283 builder.clearAccessChain();
2284 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002285 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002286
John Kesseniche485c7a2017-05-31 18:50:53 -06002287 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002288 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002289 TranslateNoContractionDecoration(node->getType().getQualifier()),
2290 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002291 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002292 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002293 left->getType().getBasicType(), reduceComparison);
2294
2295 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002296 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002297 builder.clearAccessChain();
2298 builder.setAccessChainRValue(result);
2299
2300 return false;
2301 }
2302
John Kessenich426394d2015-07-23 10:22:48 -06002303 //
2304 // Create the list of operands.
2305 //
John Kessenich140f3df2015-06-26 16:58:36 -06002306 glslang::TIntermSequence& glslangOperands = node->getSequence();
2307 std::vector<spv::Id> operands;
2308 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002309 // special case l-value operands; there are just a few
2310 bool lvalue = false;
2311 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002312 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002313 case glslang::EOpModf:
2314 if (arg == 1)
2315 lvalue = true;
2316 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002317 case glslang::EOpInterpolateAtSample:
2318 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002319#ifdef AMD_EXTENSIONS
2320 case glslang::EOpInterpolateAtVertex:
2321#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002322 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002323 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002324
2325 // Does it need a swizzle inversion? If so, evaluation is inverted;
2326 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002327 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002328 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2329 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2330 }
Rex Xu7a26c172015-12-08 17:12:09 +08002331 break;
Rex Xud4782c12015-09-06 16:30:11 +08002332 case glslang::EOpAtomicAdd:
2333 case glslang::EOpAtomicMin:
2334 case glslang::EOpAtomicMax:
2335 case glslang::EOpAtomicAnd:
2336 case glslang::EOpAtomicOr:
2337 case glslang::EOpAtomicXor:
2338 case glslang::EOpAtomicExchange:
2339 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002340 case glslang::EOpAtomicLoad:
2341 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002342 case glslang::EOpAtomicCounterAdd:
2343 case glslang::EOpAtomicCounterSubtract:
2344 case glslang::EOpAtomicCounterMin:
2345 case glslang::EOpAtomicCounterMax:
2346 case glslang::EOpAtomicCounterAnd:
2347 case glslang::EOpAtomicCounterOr:
2348 case glslang::EOpAtomicCounterXor:
2349 case glslang::EOpAtomicCounterExchange:
2350 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002351 if (arg == 0)
2352 lvalue = true;
2353 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002354 case glslang::EOpAddCarry:
2355 case glslang::EOpSubBorrow:
2356 if (arg == 2)
2357 lvalue = true;
2358 break;
2359 case glslang::EOpUMulExtended:
2360 case glslang::EOpIMulExtended:
2361 if (arg >= 2)
2362 lvalue = true;
2363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 default:
2365 break;
2366 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002367 builder.clearAccessChain();
2368 if (invertedType != spv::NoType && arg == 0)
2369 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2370 else
2371 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002372 if (lvalue)
2373 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002374 else {
2375 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002376 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002377 }
John Kessenich140f3df2015-06-26 16:58:36 -06002378 }
John Kessenich426394d2015-07-23 10:22:48 -06002379
John Kesseniche485c7a2017-05-31 18:50:53 -06002380 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002381 if (atomic) {
2382 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002383 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002384 } else {
2385 // Pass through to generic operations.
2386 switch (glslangOperands.size()) {
2387 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002388 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002389 break;
2390 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002391 {
2392 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002393 TranslateNoContractionDecoration(node->getType().getQualifier()),
2394 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002395 result = createUnaryOperation(
2396 node->getOp(), decorations,
2397 resultType(), operands.front(),
2398 glslangOperands[0]->getAsTyped()->getBasicType());
2399 }
John Kessenich426394d2015-07-23 10:22:48 -06002400 break;
2401 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002402 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002403 break;
2404 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002405 if (invertedType)
2406 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 }
2408
2409 if (noReturnValue)
2410 return false;
2411
2412 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002413 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002414 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002415 } else {
2416 builder.clearAccessChain();
2417 builder.setAccessChainRValue(result);
2418 return false;
2419 }
2420}
2421
John Kessenich433e9ff2017-01-26 20:31:11 -07002422// This path handles both if-then-else and ?:
2423// The if-then-else has a node type of void, while
2424// ?: has either a void or a non-void node type
2425//
2426// Leaving the result, when not void:
2427// GLSL only has r-values as the result of a :?, but
2428// if we have an l-value, that can be more efficient if it will
2429// become the base of a complex r-value expression, because the
2430// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002431bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2432{
John Kessenich4bee5312018-02-20 21:29:05 -07002433 // See if it simple and safe, or required, to execute both sides.
2434 // Crucially, side effects must be either semantically required or avoided,
2435 // and there are performance trade-offs.
2436 // Return true if required or a good idea (and safe) to execute both sides,
2437 // false otherwise.
2438 const auto bothSidesPolicy = [&]() -> bool {
2439 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002440 if (node->getTrueBlock() == nullptr ||
2441 node->getFalseBlock() == nullptr)
2442 return false;
2443
John Kessenich4bee5312018-02-20 21:29:05 -07002444 // required? (unless we write additional code to look for side effects
2445 // and make performance trade-offs if none are present)
2446 if (!node->getShortCircuit())
2447 return true;
2448
2449 // if not required to execute both, decide based on performance/practicality...
2450
2451 // see if OpSelect can handle it
2452 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2453 node->getBasicType() == glslang::EbtVoid)
2454 return false;
2455
John Kessenich433e9ff2017-01-26 20:31:11 -07002456 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2457 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2458
2459 // return true if a single operand to ? : is okay for OpSelect
2460 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002461 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002462 };
2463
2464 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2465 operandOkay(node->getFalseBlock()->getAsTyped());
2466 };
2467
John Kessenich4bee5312018-02-20 21:29:05 -07002468 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2469 // emit the condition before doing anything with selection
2470 node->getCondition()->traverse(this);
2471 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2472
2473 // Find a way of executing both sides and selecting the right result.
2474 const auto executeBothSides = [&]() -> void {
2475 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002476 node->getTrueBlock()->traverse(this);
2477 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2478 node->getFalseBlock()->traverse(this);
2479 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2480
John Kesseniche485c7a2017-05-31 18:50:53 -06002481 builder.setLine(node->getLoc().line);
2482
John Kessenich4bee5312018-02-20 21:29:05 -07002483 // done if void
2484 if (node->getBasicType() == glslang::EbtVoid)
2485 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002486
John Kessenich4bee5312018-02-20 21:29:05 -07002487 // emit code to select between trueValue and falseValue
2488
2489 // see if OpSelect can handle it
2490 if (node->getType().isScalar() || node->getType().isVector()) {
2491 // Emit OpSelect for this selection.
2492
2493 // smear condition to vector, if necessary (AST is always scalar)
2494 if (builder.isVector(trueValue))
2495 condition = builder.smearScalar(spv::NoPrecision, condition,
2496 builder.makeVectorType(builder.makeBoolType(),
2497 builder.getNumComponents(trueValue)));
2498
2499 // OpSelect
2500 result = builder.createTriOp(spv::OpSelect,
2501 convertGlslangToSpvType(node->getType()), condition,
2502 trueValue, falseValue);
2503
2504 builder.clearAccessChain();
2505 builder.setAccessChainRValue(result);
2506 } else {
2507 // We need control flow to select the result.
2508 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2509 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2510
2511 // Selection control:
2512 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2513
2514 // make an "if" based on the value created by the condition
2515 spv::Builder::If ifBuilder(condition, control, builder);
2516
2517 // emit the "then" statement
2518 builder.createStore(trueValue, result);
2519 ifBuilder.makeBeginElse();
2520 // emit the "else" statement
2521 builder.createStore(falseValue, result);
2522
2523 // finish off the control flow
2524 ifBuilder.makeEndIf();
2525
2526 builder.clearAccessChain();
2527 builder.setAccessChainLValue(result);
2528 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002529 };
2530
John Kessenich4bee5312018-02-20 21:29:05 -07002531 // Execute the one side needed, as per the condition
2532 const auto executeOneSide = [&]() {
2533 // Always emit control flow.
2534 if (node->getBasicType() != glslang::EbtVoid)
2535 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002536
John Kessenich4bee5312018-02-20 21:29:05 -07002537 // Selection control:
2538 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2539
2540 // make an "if" based on the value created by the condition
2541 spv::Builder::If ifBuilder(condition, control, builder);
2542
2543 // emit the "then" statement
2544 if (node->getTrueBlock() != nullptr) {
2545 node->getTrueBlock()->traverse(this);
2546 if (result != spv::NoResult)
2547 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2548 }
2549
2550 if (node->getFalseBlock() != nullptr) {
2551 ifBuilder.makeBeginElse();
2552 // emit the "else" statement
2553 node->getFalseBlock()->traverse(this);
2554 if (result != spv::NoResult)
2555 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2556 }
2557
2558 // finish off the control flow
2559 ifBuilder.makeEndIf();
2560
2561 if (result != spv::NoResult) {
2562 builder.clearAccessChain();
2563 builder.setAccessChainLValue(result);
2564 }
2565 };
2566
2567 // Try for OpSelect (or a requirement to execute both sides)
2568 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002569 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2570 if (node->getType().getQualifier().isSpecConstant())
2571 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002572 executeBothSides();
2573 } else
2574 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002575
2576 return false;
2577}
2578
2579bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2580{
2581 // emit and get the condition before doing anything with switch
2582 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002583 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002584
Rex Xu57e65922017-07-04 23:23:40 +08002585 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002586 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002587
John Kessenich140f3df2015-06-26 16:58:36 -06002588 // browse the children to sort out code segments
2589 int defaultSegment = -1;
2590 std::vector<TIntermNode*> codeSegments;
2591 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2592 std::vector<int> caseValues;
2593 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2594 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2595 TIntermNode* child = *c;
2596 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002597 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002598 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002599 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002600 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2601 } else
2602 codeSegments.push_back(child);
2603 }
2604
qining25262b32016-05-06 17:25:16 -04002605 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002606 // statements between the last case and the end of the switch statement
2607 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2608 (int)codeSegments.size() == defaultSegment)
2609 codeSegments.push_back(nullptr);
2610
2611 // make the switch statement
2612 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002613 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002614
2615 // emit all the code in the segments
2616 breakForLoop.push(false);
2617 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2618 builder.nextSwitchSegment(segmentBlocks, s);
2619 if (codeSegments[s])
2620 codeSegments[s]->traverse(this);
2621 else
2622 builder.addSwitchBreak();
2623 }
2624 breakForLoop.pop();
2625
2626 builder.endSwitch(segmentBlocks);
2627
2628 return false;
2629}
2630
2631void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2632{
2633 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002634 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002635
2636 builder.clearAccessChain();
2637 builder.setAccessChainRValue(constant);
2638}
2639
2640bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2641{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002642 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002643 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002644
2645 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002646 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2647 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002648
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002649 // Spec requires back edges to target header blocks, and every header block
2650 // must dominate its merge block. Make a header block first to ensure these
2651 // conditions are met. By definition, it will contain OpLoopMerge, followed
2652 // by a block-ending branch. But we don't want to put any other body/test
2653 // instructions in it, since the body/test may have arbitrary instructions,
2654 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002655 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002656 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002657 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002658 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002659 spv::Block& test = builder.makeNewBlock();
2660 builder.createBranch(&test);
2661
2662 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002663 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002664 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002665 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2666
2667 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002668 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002669 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002670 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002671 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002672 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002673
2674 builder.setBuildPoint(&blocks.continue_target);
2675 if (node->getTerminal())
2676 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002677 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002678 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002679 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002680 builder.createBranch(&blocks.body);
2681
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002682 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002683 builder.setBuildPoint(&blocks.body);
2684 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002685 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002686 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002687 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002688
2689 builder.setBuildPoint(&blocks.continue_target);
2690 if (node->getTerminal())
2691 node->getTerminal()->traverse(this);
2692 if (node->getTest()) {
2693 node->getTest()->traverse(this);
2694 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002695 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002696 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002697 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002698 // TODO: unless there was a break/return/discard instruction
2699 // somewhere in the body, this is an infinite loop, so we should
2700 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002701 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002702 }
John Kessenich140f3df2015-06-26 16:58:36 -06002703 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002704 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002705 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002706 return false;
2707}
2708
2709bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2710{
2711 if (node->getExpression())
2712 node->getExpression()->traverse(this);
2713
John Kesseniche485c7a2017-05-31 18:50:53 -06002714 builder.setLine(node->getLoc().line);
2715
John Kessenich140f3df2015-06-26 16:58:36 -06002716 switch (node->getFlowOp()) {
2717 case glslang::EOpKill:
2718 builder.makeDiscard();
2719 break;
2720 case glslang::EOpBreak:
2721 if (breakForLoop.top())
2722 builder.createLoopExit();
2723 else
2724 builder.addSwitchBreak();
2725 break;
2726 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002727 builder.createLoopContinue();
2728 break;
2729 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002730 if (node->getExpression()) {
2731 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2732 spv::Id returnId = accessChainLoad(glslangReturnType);
2733 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2734 builder.clearAccessChain();
2735 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2736 builder.setAccessChainLValue(copyId);
2737 multiTypeStore(glslangReturnType, returnId);
2738 returnId = builder.createLoad(copyId);
2739 }
2740 builder.makeReturn(false, returnId);
2741 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002742 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002743
2744 builder.clearAccessChain();
2745 break;
2746
2747 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002748 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 }
2751
2752 return false;
2753}
2754
2755spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2756{
qining25262b32016-05-06 17:25:16 -04002757 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002758 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002759 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002760 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002761 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002762 }
2763
2764 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002765 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002766 spv::Id spvType = convertGlslangToSpvType(node->getType());
2767
Rex Xucabbb782017-03-24 13:41:14 +08002768 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2769 node->getType().containsBasicType(glslang::EbtInt16) ||
2770 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002771 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002772 switch (storageClass) {
2773 case spv::StorageClassInput:
2774 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002775 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002776 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002777 break;
2778 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002779 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002780 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002781 break;
2782 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002783 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002784 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2785 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002786 else
2787 builder.addCapability(spv::CapabilityStorageUniform16);
2788 break;
2789 case spv::StorageClassStorageBuffer:
2790 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2791 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2792 break;
2793 default:
2794 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002795 }
2796 }
Rex Xuf89ad982017-04-07 23:22:33 +08002797
John Kessenich312dcfb2018-07-03 13:19:51 -06002798 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2799 node->getType().containsBasicType(glslang::EbtUint8);
2800 if (contains8BitType) {
2801 if (storageClass == spv::StorageClassPushConstant) {
2802 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2803 builder.addCapability(spv::CapabilityStoragePushConstant8);
2804 } else if (storageClass == spv::StorageClassUniform) {
2805 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2806 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2807 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2808 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2809 }
2810 }
2811
John Kessenich140f3df2015-06-26 16:58:36 -06002812 const char* name = node->getName().c_str();
2813 if (glslang::IsAnonymous(name))
2814 name = "";
2815
2816 return builder.createVariable(storageClass, spvType, name);
2817}
2818
2819// Return type Id of the sampled type.
2820spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2821{
2822 switch (sampler.type) {
2823 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002824#ifdef AMD_EXTENSIONS
2825 case glslang::EbtFloat16:
2826 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2827 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2828 return builder.makeFloatType(16);
2829#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002830 case glslang::EbtInt: return builder.makeIntType(32);
2831 case glslang::EbtUint: return builder.makeUintType(32);
2832 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002833 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002834 return builder.makeFloatType(32);
2835 }
2836}
2837
John Kessenich8c8505c2016-07-26 12:50:38 -06002838// If node is a swizzle operation, return the type that should be used if
2839// the swizzle base is first consumed by another operation, before the swizzle
2840// is applied.
2841spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2842{
John Kessenichecba76f2017-01-06 00:34:48 -07002843 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002844 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2845 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2846 else
2847 return spv::NoType;
2848}
2849
2850// When inverting a swizzle with a parent op, this function
2851// will apply the swizzle operation to a completed parent operation.
2852spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2853{
2854 std::vector<unsigned> swizzle;
2855 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2856 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2857}
2858
John Kessenich8c8505c2016-07-26 12:50:38 -06002859// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2860void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2861{
2862 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2863 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2864 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2865}
2866
John Kessenich3ac051e2015-12-20 11:29:16 -07002867// Convert from a glslang type to an SPV type, by calling into a
2868// recursive version of this function. This establishes the inherited
2869// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002870spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2871{
John Kessenichead86222018-03-28 18:01:20 -06002872 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002873}
2874
2875// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002876// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002877// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002878spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2879 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002880{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002881 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002882
2883 switch (type.getBasicType()) {
2884 case glslang::EbtVoid:
2885 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002886 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002887 break;
2888 case glslang::EbtFloat:
2889 spvType = builder.makeFloatType(32);
2890 break;
2891 case glslang::EbtDouble:
2892 spvType = builder.makeFloatType(64);
2893 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002894 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002895 spvType = builder.makeFloatType(16);
2896 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002897 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002898 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2899 // a 32-bit int where non-0 means true.
2900 if (explicitLayout != glslang::ElpNone)
2901 spvType = builder.makeUintType(32);
2902 else
2903 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002904 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002905 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002906 spvType = builder.makeIntType(8);
2907 break;
2908 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002909 spvType = builder.makeUintType(8);
2910 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002911 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002912 spvType = builder.makeIntType(16);
2913 break;
2914 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002915 spvType = builder.makeUintType(16);
2916 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002917 case glslang::EbtInt:
2918 spvType = builder.makeIntType(32);
2919 break;
2920 case glslang::EbtUint:
2921 spvType = builder.makeUintType(32);
2922 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002923 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002924 spvType = builder.makeIntType(64);
2925 break;
2926 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002927 spvType = builder.makeUintType(64);
2928 break;
John Kessenich426394d2015-07-23 10:22:48 -06002929 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002930 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002931 spvType = builder.makeUintType(32);
2932 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002933#ifdef NV_EXTENSIONS
2934 case glslang::EbtAccStructNV:
2935 spvType = builder.makeAccelerationStructureNVType();
2936 break;
2937#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002938 case glslang::EbtSampler:
2939 {
2940 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002941 if (sampler.sampler) {
2942 // pure sampler
2943 spvType = builder.makeSamplerType();
2944 } else {
2945 // an image is present, make its type
2946 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2947 sampler.image ? 2 : 1, TranslateImageFormat(type));
2948 if (sampler.combined) {
2949 // already has both image and sampler, make the combined type
2950 spvType = builder.makeSampledImageType(spvType);
2951 }
John Kessenich55e7d112015-11-15 21:33:39 -07002952 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002953 }
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955 case glslang::EbtStruct:
2956 case glslang::EbtBlock:
2957 {
2958 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002959 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002960
2961 // Try to share structs for different layouts, but not yet for other
2962 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002963 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002964 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002965 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967
2968 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002969 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002970 memberRemapper[glslangMembers].resize(glslangMembers->size());
2971 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002972 }
2973 break;
2974 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002975 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 }
2978
2979 if (type.isMatrix())
2980 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2981 else {
2982 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2983 if (type.getVectorSize() > 1)
2984 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2985 }
2986
2987 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002988 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2989
John Kessenichc9a80832015-09-12 12:17:44 -06002990 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002991 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002992 // We need to decorate array strides for types needing explicit layout, except blocks.
2993 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002994 // Use a dummy glslang type for querying internal strides of
2995 // arrays of arrays, but using just a one-dimensional array.
2996 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002997 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2998 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002999
3000 // Will compute the higher-order strides here, rather than making a whole
3001 // pile of types and doing repetitive recursion on their contents.
3002 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3003 }
John Kessenichf8842e52016-01-04 19:22:56 -07003004
3005 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003006 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003007 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003008 if (stride > 0)
3009 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003010 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003011 }
3012 } else {
3013 // single-dimensional array, and don't yet have stride
3014
John Kessenichf8842e52016-01-04 19:22:56 -07003015 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003016 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3017 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003018 }
John Kessenich31ed4832015-09-09 17:51:38 -06003019
John Kessenichead86222018-03-28 18:01:20 -06003020 // Do the outer dimension, which might not be known for a runtime-sized array.
3021 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3022 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003023 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003024 else {
3025 if (!lastBufferBlockMember) {
3026 builder.addExtension("SPV_EXT_descriptor_indexing");
3027 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3028 }
John Kessenichead86222018-03-28 18:01:20 -06003029 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003030 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003031 if (stride > 0)
3032 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003033 }
3034
3035 return spvType;
3036}
3037
John Kessenich0e737842017-03-24 18:38:16 -06003038// TODO: this functionality should exist at a higher level, in creating the AST
3039//
3040// Identify interface members that don't have their required extension turned on.
3041//
3042bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3043{
Chao Chen3c366992018-09-19 11:41:59 -07003044#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003045 auto& extensions = glslangIntermediate->getRequestedExtensions();
3046
Rex Xubcf291a2017-03-29 23:01:36 +08003047 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3048 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3049 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003050 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3051 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3052 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003053
3054 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3055 if (member.getFieldName() == "gl_ViewportMask" &&
3056 extensions.find("GL_NV_viewport_array2") == extensions.end())
3057 return true;
3058 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3059 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3060 return true;
3061 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3062 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3063 return true;
3064 }
3065#endif
John Kessenich0e737842017-03-24 18:38:16 -06003066
3067 return false;
3068};
3069
John Kessenich6090df02016-06-30 21:18:02 -06003070// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3071// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3072// Mutually recursive with convertGlslangToSpvType().
3073spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3074 const glslang::TTypeList* glslangMembers,
3075 glslang::TLayoutPacking explicitLayout,
3076 const glslang::TQualifier& qualifier)
3077{
3078 // Create a vector of struct types for SPIR-V to consume
3079 std::vector<spv::Id> spvMembers;
3080 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 -06003081 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3082 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3083 if (glslangMember.hiddenMember()) {
3084 ++memberDelta;
3085 if (type.getBasicType() == glslang::EbtBlock)
3086 memberRemapper[glslangMembers][i] = -1;
3087 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003088 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003089 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003090 if (filterMember(glslangMember))
3091 continue;
3092 }
John Kessenich6090df02016-06-30 21:18:02 -06003093 // modify just this child's view of the qualifier
3094 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3095 InheritQualifiers(memberQualifier, qualifier);
3096
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003097 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003098 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003099 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003100
3101 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003102 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3103 i == (int)glslangMembers->size() - 1;
3104 spvMembers.push_back(
3105 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003106 }
3107 }
3108
3109 // Make the SPIR-V type
3110 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003111 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003112 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3113
3114 // Decorate it
3115 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3116
3117 return spvType;
3118}
3119
3120void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3121 const glslang::TTypeList* glslangMembers,
3122 glslang::TLayoutPacking explicitLayout,
3123 const glslang::TQualifier& qualifier,
3124 spv::Id spvType)
3125{
3126 // Name and decorate the non-hidden members
3127 int offset = -1;
3128 int locationOffset = 0; // for use within the members of this struct
3129 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3130 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3131 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003132 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003133 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003134 if (filterMember(glslangMember))
3135 continue;
3136 }
John Kessenich6090df02016-06-30 21:18:02 -06003137
3138 // modify just this child's view of the qualifier
3139 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3140 InheritQualifiers(memberQualifier, qualifier);
3141
3142 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003143 if (member < 0)
3144 continue;
3145
3146 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3147 builder.addMemberDecoration(spvType, member,
3148 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3149 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3150 // Add interpolation and auxiliary storage decorations only to
3151 // top-level members of Input and Output storage classes
3152 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3153 type.getQualifier().storage == glslang::EvqVaryingOut) {
3154 if (type.getBasicType() == glslang::EbtBlock ||
3155 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3156 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3157 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003158#ifdef NV_EXTENSIONS
3159 addMeshNVDecoration(spvType, member, memberQualifier);
3160#endif
John Kessenich6090df02016-06-30 21:18:02 -06003161 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003162 }
3163 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003164
John Kessenich5d610ee2018-03-07 18:05:55 -07003165 if (type.getBasicType() == glslang::EbtBlock &&
3166 qualifier.storage == glslang::EvqBuffer) {
3167 // Add memory decorations only to top-level members of shader storage block
3168 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003169 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003170 for (unsigned int i = 0; i < memory.size(); ++i)
3171 builder.addMemberDecoration(spvType, member, memory[i]);
3172 }
John Kessenich6090df02016-06-30 21:18:02 -06003173
John Kessenich5d610ee2018-03-07 18:05:55 -07003174 // Location assignment was already completed correctly by the front end,
3175 // just track whether a member needs to be decorated.
3176 // Ignore member locations if the container is an array, as that's
3177 // ill-specified and decisions have been made to not allow this.
3178 if (! type.isArray() && memberQualifier.hasLocation())
3179 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003180
John Kessenich5d610ee2018-03-07 18:05:55 -07003181 if (qualifier.hasLocation()) // track for upcoming inheritance
3182 locationOffset += glslangIntermediate->computeTypeLocationSize(
3183 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003184
John Kessenich5d610ee2018-03-07 18:05:55 -07003185 // component, XFB, others
3186 if (glslangMember.getQualifier().hasComponent())
3187 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3188 glslangMember.getQualifier().layoutComponent);
3189 if (glslangMember.getQualifier().hasXfbOffset())
3190 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3191 glslangMember.getQualifier().layoutXfbOffset);
3192 else if (explicitLayout != glslang::ElpNone) {
3193 // figure out what to do with offset, which is accumulating
3194 int nextOffset;
3195 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3196 if (offset >= 0)
3197 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3198 offset = nextOffset;
3199 }
John Kessenich6090df02016-06-30 21:18:02 -06003200
John Kessenich5d610ee2018-03-07 18:05:55 -07003201 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3202 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3203 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003204
John Kessenich5d610ee2018-03-07 18:05:55 -07003205 // built-in variable decorations
3206 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3207 if (builtIn != spv::BuiltInMax)
3208 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003209
John Kessenich5611c6d2018-04-05 11:25:02 -06003210 // nonuniform
3211 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3212
John Kessenichead86222018-03-28 18:01:20 -06003213 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3214 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3215 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3216 memberQualifier.semanticName);
3217 }
3218
chaoc771d89f2017-01-13 01:10:53 -08003219#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003220 if (builtIn == spv::BuiltInLayer) {
3221 // SPV_NV_viewport_array2 extension
3222 if (glslangMember.getQualifier().layoutViewportRelative){
3223 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3224 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3225 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003226 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003227 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3228 builder.addMemberDecoration(spvType, member,
3229 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3230 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3231 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3232 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003233 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003234 }
3235 if (glslangMember.getQualifier().layoutPassthrough) {
3236 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3237 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3238 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3239 }
chaoc771d89f2017-01-13 01:10:53 -08003240#endif
John Kessenich6090df02016-06-30 21:18:02 -06003241 }
3242
3243 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003244 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3245 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003246 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3247 builder.addCapability(spv::CapabilityGeometryStreams);
3248 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3249 }
John Kessenich6090df02016-06-30 21:18:02 -06003250}
3251
John Kessenich6c292d32016-02-15 20:58:50 -07003252// Turn the expression forming the array size into an id.
3253// This is not quite trivial, because of specialization constants.
3254// Sometimes, a raw constant is turned into an Id, and sometimes
3255// a specialization constant expression is.
3256spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3257{
3258 // First, see if this is sized with a node, meaning a specialization constant:
3259 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3260 if (specNode != nullptr) {
3261 builder.clearAccessChain();
3262 specNode->traverse(this);
3263 return accessChainLoad(specNode->getAsTyped()->getType());
3264 }
qining25262b32016-05-06 17:25:16 -04003265
John Kessenich6c292d32016-02-15 20:58:50 -07003266 // Otherwise, need a compile-time (front end) size, get it:
3267 int size = arraySizes.getDimSize(dim);
3268 assert(size > 0);
3269 return builder.makeUintConstant(size);
3270}
3271
John Kessenich103bef92016-02-08 21:38:15 -07003272// Wrap the builder's accessChainLoad to:
3273// - localize handling of RelaxedPrecision
3274// - use the SPIR-V inferred type instead of another conversion of the glslang type
3275// (avoids unnecessary work and possible type punning for structures)
3276// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003277spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3278{
John Kessenich103bef92016-02-08 21:38:15 -07003279 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003280
3281 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3282 coherentFlags |= TranslateCoherent(type);
3283
John Kessenich5611c6d2018-04-05 11:25:02 -06003284 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003285 TranslateNonUniformDecoration(type.getQualifier()),
3286 nominalTypeId,
3287 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3288 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003289
3290 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003291 if (type.getBasicType() == glslang::EbtBool) {
3292 if (builder.isScalarType(nominalTypeId)) {
3293 // Conversion for bool
3294 spv::Id boolType = builder.makeBoolType();
3295 if (nominalTypeId != boolType)
3296 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3297 } else if (builder.isVectorType(nominalTypeId)) {
3298 // Conversion for bvec
3299 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3300 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3301 if (nominalTypeId != bvecType)
3302 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3303 }
3304 }
John Kessenich103bef92016-02-08 21:38:15 -07003305
3306 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003307}
3308
Rex Xu27253232016-02-23 17:51:09 +08003309// Wrap the builder's accessChainStore to:
3310// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003311//
3312// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003313void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3314{
3315 // Need to convert to abstract types when necessary
3316 if (type.getBasicType() == glslang::EbtBool) {
3317 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3318
3319 if (builder.isScalarType(nominalTypeId)) {
3320 // Conversion for bool
3321 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003322 if (nominalTypeId != boolType) {
3323 // keep these outside arguments, for determinant order-of-evaluation
3324 spv::Id one = builder.makeUintConstant(1);
3325 spv::Id zero = builder.makeUintConstant(0);
3326 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3327 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003328 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003329 } else if (builder.isVectorType(nominalTypeId)) {
3330 // Conversion for bvec
3331 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3332 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003333 if (nominalTypeId != bvecType) {
3334 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003335 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3336 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3337 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003338 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003339 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3340 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003341 }
3342 }
3343
Jeff Bolz36831c92018-09-05 10:11:41 -05003344 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3345 coherentFlags |= TranslateCoherent(type);
3346
3347 builder.accessChainStore(rvalue,
3348 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3349 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003350}
3351
John Kessenich4bf71552016-09-02 11:20:21 -06003352// For storing when types match at the glslang level, but not might match at the
3353// SPIR-V level.
3354//
3355// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003356// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003357// as in a member-decorated way.
3358//
3359// NOTE: This function can handle any store request; if it's not special it
3360// simplifies to a simple OpStore.
3361//
3362// Implicitly uses the existing builder.accessChain as the storage target.
3363void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3364{
John Kessenichb3e24e42016-09-11 12:33:43 -06003365 // we only do the complex path here if it's an aggregate
3366 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003367 accessChainStore(type, rValue);
3368 return;
3369 }
3370
John Kessenichb3e24e42016-09-11 12:33:43 -06003371 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003372 spv::Id rType = builder.getTypeId(rValue);
3373 spv::Id lValue = builder.accessChainGetLValue();
3374 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3375 if (lType == rType) {
3376 accessChainStore(type, rValue);
3377 return;
3378 }
3379
John Kessenichb3e24e42016-09-11 12:33:43 -06003380 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003381 // where the two types were the same type in GLSL. This requires member
3382 // by member copy, recursively.
3383
John Kessenichb3e24e42016-09-11 12:33:43 -06003384 // If an array, copy element by element.
3385 if (type.isArray()) {
3386 glslang::TType glslangElementType(type, 0);
3387 spv::Id elementRType = builder.getContainedTypeId(rType);
3388 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3389 // get the source member
3390 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003391
John Kessenichb3e24e42016-09-11 12:33:43 -06003392 // set up the target storage
3393 builder.clearAccessChain();
3394 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003395 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003396
John Kessenichb3e24e42016-09-11 12:33:43 -06003397 // store the member
3398 multiTypeStore(glslangElementType, elementRValue);
3399 }
3400 } else {
3401 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003402
John Kessenichb3e24e42016-09-11 12:33:43 -06003403 // loop over structure members
3404 const glslang::TTypeList& members = *type.getStruct();
3405 for (int m = 0; m < (int)members.size(); ++m) {
3406 const glslang::TType& glslangMemberType = *members[m].type;
3407
3408 // get the source member
3409 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3410 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3411
3412 // set up the target storage
3413 builder.clearAccessChain();
3414 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003415 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003416
3417 // store the member
3418 multiTypeStore(glslangMemberType, memberRValue);
3419 }
John Kessenich4bf71552016-09-02 11:20:21 -06003420 }
3421}
3422
John Kessenichf85e8062015-12-19 13:57:10 -07003423// Decide whether or not this type should be
3424// decorated with offsets and strides, and if so
3425// whether std140 or std430 rules should be applied.
3426glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003427{
John Kessenichf85e8062015-12-19 13:57:10 -07003428 // has to be a block
3429 if (type.getBasicType() != glslang::EbtBlock)
3430 return glslang::ElpNone;
3431
Chao Chen3c366992018-09-19 11:41:59 -07003432 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003433 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003434 type.getQualifier().storage != glslang::EvqBuffer &&
3435 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003436 return glslang::ElpNone;
3437
3438 // return the layout to use
3439 switch (type.getQualifier().layoutPacking) {
3440 case glslang::ElpStd140:
3441 case glslang::ElpStd430:
3442 return type.getQualifier().layoutPacking;
3443 default:
3444 return glslang::ElpNone;
3445 }
John Kessenich31ed4832015-09-09 17:51:38 -06003446}
3447
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003448// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003449int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003450{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003451 int size;
John Kessenich49987892015-12-29 17:11:44 -07003452 int stride;
3453 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003454
3455 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003456}
3457
John Kessenich49987892015-12-29 17:11:44 -07003458// 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 -07003459// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003460int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003461{
John Kessenich49987892015-12-29 17:11:44 -07003462 glslang::TType elementType;
3463 elementType.shallowCopy(matrixType);
3464 elementType.clearArraySizes();
3465
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003466 int size;
John Kessenich49987892015-12-29 17:11:44 -07003467 int stride;
3468 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3469
3470 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003471}
3472
John Kessenich5e4b1242015-08-06 22:53:06 -06003473// Given a member type of a struct, realign the current offset for it, and compute
3474// the next (not yet aligned) offset for the next member, which will get aligned
3475// on the next call.
3476// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3477// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3478// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003479void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003480 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003481{
3482 // this will get a positive value when deemed necessary
3483 nextOffset = -1;
3484
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 // override anything in currentOffset with user-set offset
3486 if (memberType.getQualifier().hasOffset())
3487 currentOffset = memberType.getQualifier().layoutOffset;
3488
3489 // It could be that current linker usage in glslang updated all the layoutOffset,
3490 // in which case the following code does not matter. But, that's not quite right
3491 // once cross-compilation unit GLSL validation is done, as the original user
3492 // settings are needed in layoutOffset, and then the following will come into play.
3493
John Kessenichf85e8062015-12-19 13:57:10 -07003494 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 if (! memberType.getQualifier().hasOffset())
3496 currentOffset = -1;
3497
3498 return;
3499 }
3500
John Kessenichf85e8062015-12-19 13:57:10 -07003501 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003502 if (currentOffset < 0)
3503 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003504
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3506 // but possibly not yet correctly aligned.
3507
3508 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003509 int dummyStride;
3510 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003511
3512 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003513 // TODO: make this consistent in early phases of code:
3514 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3515 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3516 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003517 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003518 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003519 int dummySize;
3520 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3521 if (componentAlignment <= 4)
3522 memberAlignment = componentAlignment;
3523 }
3524
3525 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003526 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003527
3528 // Bump up to vec4 if there is a bad straddle
3529 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3530 glslang::RoundToPow2(currentOffset, 16);
3531
John Kessenich5e4b1242015-08-06 22:53:06 -06003532 nextOffset = currentOffset + memberSize;
3533}
3534
David Netoa901ffe2016-06-08 14:11:40 +01003535void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003536{
David Netoa901ffe2016-06-08 14:11:40 +01003537 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3538 switch (glslangBuiltIn)
3539 {
3540 case glslang::EbvClipDistance:
3541 case glslang::EbvCullDistance:
3542 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003543#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003544 case glslang::EbvViewportMaskNV:
3545 case glslang::EbvSecondaryPositionNV:
3546 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003547 case glslang::EbvPositionPerViewNV:
3548 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003549 case glslang::EbvTaskCountNV:
3550 case glslang::EbvPrimitiveCountNV:
3551 case glslang::EbvPrimitiveIndicesNV:
3552 case glslang::EbvClipDistancePerViewNV:
3553 case glslang::EbvCullDistancePerViewNV:
3554 case glslang::EbvLayerPerViewNV:
3555 case glslang::EbvMeshViewCountNV:
3556 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003557#endif
David Netoa901ffe2016-06-08 14:11:40 +01003558 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3559 // Alternately, we could just call this for any glslang built-in, since the
3560 // capability already guards against duplicates.
3561 TranslateBuiltInDecoration(glslangBuiltIn, false);
3562 break;
3563 default:
3564 // Capabilities were already generated when the struct was declared.
3565 break;
3566 }
John Kessenichebb50532016-05-16 19:22:05 -06003567}
3568
John Kessenich6fccb3c2016-09-19 16:01:41 -06003569bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003570{
John Kessenicheee9d532016-09-19 18:09:30 -06003571 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003572}
3573
John Kessenichd41993d2017-09-10 15:21:05 -06003574// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003575// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3576// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003577bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003578{
John Kessenich6a14f782017-12-04 02:48:10 -07003579 assert(qualifier == glslang::EvqIn ||
3580 qualifier == glslang::EvqOut ||
3581 qualifier == glslang::EvqInOut ||
3582 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003583 return qualifier != glslang::EvqConstReadOnly;
3584}
3585
3586// Is parameter pass-by-original?
3587bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3588 bool implicitThisParam)
3589{
3590 if (implicitThisParam) // implicit this
3591 return true;
3592 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003593 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003594 return paramType.containsOpaque() || // sampler, etc.
3595 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3596}
3597
John Kessenich140f3df2015-06-26 16:58:36 -06003598// Make all the functions, skeletally, without actually visiting their bodies.
3599void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3600{
Jeff Bolz36831c92018-09-05 10:11:41 -05003601 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003602 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3603 if (paramPrecision != spv::NoPrecision)
3604 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003605 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003606 };
3607
John Kessenich140f3df2015-06-26 16:58:36 -06003608 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3609 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003610 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003611 continue;
3612
3613 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003614 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003615 //
qining25262b32016-05-06 17:25:16 -04003616 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003617 // function. What it is an address of varies:
3618 //
John Kessenich4bf71552016-09-02 11:20:21 -06003619 // - "in" parameters not marked as "const" can be written to without modifying the calling
3620 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003621 //
3622 // - "const in" parameters can just be the r-value, as no writes need occur.
3623 //
John Kessenich4bf71552016-09-02 11:20:21 -06003624 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3625 // 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 -06003626
3627 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003628 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003629 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3630
John Kessenichfad62972017-07-18 02:35:46 -06003631 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3632 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003633
John Kessenichfad62972017-07-18 02:35:46 -06003634 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003635 for (int p = 0; p < (int)parameters.size(); ++p) {
3636 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3637 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003638 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003639 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003640 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003641 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3642 else
John Kessenich4bf71552016-09-02 11:20:21 -06003643 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003644 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003645 paramTypes.push_back(typeId);
3646 }
3647
3648 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003649 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3650 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003651 glslFunction->getName().c_str(), paramTypes,
3652 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003653 if (implicitThis)
3654 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003655
3656 // Track function to emit/call later
3657 functionMap[glslFunction->getName().c_str()] = function;
3658
3659 // Set the parameter id's
3660 for (int p = 0; p < (int)parameters.size(); ++p) {
3661 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3662 // give a name too
3663 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3664 }
3665 }
3666}
3667
3668// Process all the initializers, while skipping the functions and link objects
3669void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3670{
3671 builder.setBuildPoint(shaderEntry->getLastBlock());
3672 for (int i = 0; i < (int)initializers.size(); ++i) {
3673 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3674 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3675
3676 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003677 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003678 initializer->traverse(this);
3679 }
3680 }
3681}
3682
3683// Process all the functions, while skipping initializers.
3684void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3685{
3686 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3687 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003688 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003689 node->traverse(this);
3690 }
3691}
3692
3693void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3694{
qining25262b32016-05-06 17:25:16 -04003695 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003696 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003697 currentFunction = functionMap[node->getName().c_str()];
3698 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003699 builder.setBuildPoint(functionBlock);
3700}
3701
Rex Xu04db3f52015-09-16 11:44:02 +08003702void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003703{
Rex Xufc618912015-09-09 16:42:49 +08003704 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003705
3706 glslang::TSampler sampler = {};
3707 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003708#ifdef AMD_EXTENSIONS
3709 bool f16ShadowCompare = false;
3710#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003711 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003712 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3713 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003714#ifdef AMD_EXTENSIONS
3715 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3716#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003717 }
3718
John Kessenich140f3df2015-06-26 16:58:36 -06003719 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3720 builder.clearAccessChain();
3721 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003722
3723 // Special case l-value operands
3724 bool lvalue = false;
3725 switch (node.getOp()) {
3726 case glslang::EOpImageAtomicAdd:
3727 case glslang::EOpImageAtomicMin:
3728 case glslang::EOpImageAtomicMax:
3729 case glslang::EOpImageAtomicAnd:
3730 case glslang::EOpImageAtomicOr:
3731 case glslang::EOpImageAtomicXor:
3732 case glslang::EOpImageAtomicExchange:
3733 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003734 case glslang::EOpImageAtomicLoad:
3735 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003736 if (i == 0)
3737 lvalue = true;
3738 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003739 case glslang::EOpSparseImageLoad:
3740 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3741 lvalue = true;
3742 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003743#ifdef AMD_EXTENSIONS
3744 case glslang::EOpSparseTexture:
3745 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3746 lvalue = true;
3747 break;
3748 case glslang::EOpSparseTextureClamp:
3749 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3750 lvalue = true;
3751 break;
3752 case glslang::EOpSparseTextureLod:
3753 case glslang::EOpSparseTextureOffset:
3754 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3755 lvalue = true;
3756 break;
3757#else
Rex Xu48edadf2015-12-31 16:11:41 +08003758 case glslang::EOpSparseTexture:
3759 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3760 lvalue = true;
3761 break;
3762 case glslang::EOpSparseTextureClamp:
3763 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3764 lvalue = true;
3765 break;
3766 case glslang::EOpSparseTextureLod:
3767 case glslang::EOpSparseTextureOffset:
3768 if (i == 3)
3769 lvalue = true;
3770 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003771#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003772 case glslang::EOpSparseTextureFetch:
3773 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3774 lvalue = true;
3775 break;
3776 case glslang::EOpSparseTextureFetchOffset:
3777 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3778 lvalue = true;
3779 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003780#ifdef AMD_EXTENSIONS
3781 case glslang::EOpSparseTextureLodOffset:
3782 case glslang::EOpSparseTextureGrad:
3783 case glslang::EOpSparseTextureOffsetClamp:
3784 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3785 lvalue = true;
3786 break;
3787 case glslang::EOpSparseTextureGradOffset:
3788 case glslang::EOpSparseTextureGradClamp:
3789 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3790 lvalue = true;
3791 break;
3792 case glslang::EOpSparseTextureGradOffsetClamp:
3793 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3794 lvalue = true;
3795 break;
3796#else
Rex Xu48edadf2015-12-31 16:11:41 +08003797 case glslang::EOpSparseTextureLodOffset:
3798 case glslang::EOpSparseTextureGrad:
3799 case glslang::EOpSparseTextureOffsetClamp:
3800 if (i == 4)
3801 lvalue = true;
3802 break;
3803 case glslang::EOpSparseTextureGradOffset:
3804 case glslang::EOpSparseTextureGradClamp:
3805 if (i == 5)
3806 lvalue = true;
3807 break;
3808 case glslang::EOpSparseTextureGradOffsetClamp:
3809 if (i == 6)
3810 lvalue = true;
3811 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003812#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003813 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003814 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3815 lvalue = true;
3816 break;
3817 case glslang::EOpSparseTextureGatherOffset:
3818 case glslang::EOpSparseTextureGatherOffsets:
3819 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3820 lvalue = true;
3821 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003822#ifdef AMD_EXTENSIONS
3823 case glslang::EOpSparseTextureGatherLod:
3824 if (i == 3)
3825 lvalue = true;
3826 break;
3827 case glslang::EOpSparseTextureGatherLodOffset:
3828 case glslang::EOpSparseTextureGatherLodOffsets:
3829 if (i == 4)
3830 lvalue = true;
3831 break;
Rex Xu129799a2017-07-05 17:23:28 +08003832 case glslang::EOpSparseImageLoadLod:
3833 if (i == 3)
3834 lvalue = true;
3835 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003836#endif
Chao Chen3a137962018-09-19 11:41:27 -07003837#ifdef NV_EXTENSIONS
3838 case glslang::EOpImageSampleFootprintNV:
3839 if (i == 4)
3840 lvalue = true;
3841 break;
3842 case glslang::EOpImageSampleFootprintClampNV:
3843 case glslang::EOpImageSampleFootprintLodNV:
3844 if (i == 5)
3845 lvalue = true;
3846 break;
3847 case glslang::EOpImageSampleFootprintGradNV:
3848 if (i == 6)
3849 lvalue = true;
3850 break;
3851 case glslang::EOpImageSampleFootprintGradClampNV:
3852 if (i == 7)
3853 lvalue = true;
3854 break;
3855#endif
Rex Xufc618912015-09-09 16:42:49 +08003856 default:
3857 break;
3858 }
3859
Rex Xu6b86d492015-09-16 17:48:22 +08003860 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003861 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003862 else
John Kessenich32cfd492016-02-02 12:37:46 -07003863 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003864 }
3865}
3866
John Kessenichfc51d282015-08-19 13:34:18 -06003867void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003868{
John Kessenichfc51d282015-08-19 13:34:18 -06003869 builder.clearAccessChain();
3870 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003871 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003872}
John Kessenich140f3df2015-06-26 16:58:36 -06003873
John Kessenichfc51d282015-08-19 13:34:18 -06003874spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3875{
John Kesseniche485c7a2017-05-31 18:50:53 -06003876 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003877 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003878
3879 builder.setLine(node->getLoc().line);
3880
John Kessenichfc51d282015-08-19 13:34:18 -06003881 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003882
3883 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3884 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3885 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003886#ifdef AMD_EXTENSIONS
3887 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3888 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3889 : false;
3890#endif
3891
John Kessenichfc51d282015-08-19 13:34:18 -06003892 std::vector<spv::Id> arguments;
3893 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003894 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003895 else
3896 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003897 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003898
3899 spv::Builder::TextureParameters params = { };
3900 params.sampler = arguments[0];
3901
Rex Xu04db3f52015-09-16 11:44:02 +08003902 glslang::TCrackedTextureOp cracked;
3903 node->crackTexture(sampler, cracked);
3904
amhagan05506bb2017-06-13 16:53:02 -04003905 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003906
John Kessenichfc51d282015-08-19 13:34:18 -06003907 // Check for queries
3908 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003909 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3910 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003911 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003912
John Kessenichfc51d282015-08-19 13:34:18 -06003913 switch (node->getOp()) {
3914 case glslang::EOpImageQuerySize:
3915 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003916 if (arguments.size() > 1) {
3917 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003918 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003919 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003920 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003921 case glslang::EOpImageQuerySamples:
3922 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003923 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003924 case glslang::EOpTextureQueryLod:
3925 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003926 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003927 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003928 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003929 case glslang::EOpSparseTexelsResident:
3930 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003931 default:
3932 assert(0);
3933 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003934 }
John Kessenich140f3df2015-06-26 16:58:36 -06003935 }
3936
LoopDawg4425f242018-02-18 11:40:01 -07003937 int components = node->getType().getVectorSize();
3938
3939 if (node->getOp() == glslang::EOpTextureFetch) {
3940 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3941 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3942 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3943 // here around e.g. which ones return scalars or other types.
3944 components = 4;
3945 }
3946
3947 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3948
3949 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3950
Rex Xufc618912015-09-09 16:42:49 +08003951 // Check for image functions other than queries
3952 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003953 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003954 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003955 spv::IdImmediate image = { true, *(opIt++) };
3956 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003957
3958 // Handle subpass operations
3959 // TODO: GLSL should change to have the "MS" only on the type rather than the
3960 // built-in function.
3961 if (cracked.subpass) {
3962 // add on the (0,0) coordinate
3963 spv::Id zero = builder.makeIntConstant(0);
3964 std::vector<spv::Id> comps;
3965 comps.push_back(zero);
3966 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003967 spv::IdImmediate coord = { true,
3968 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3969 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003970 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003971 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3972 operands.push_back(imageOperands);
3973 spv::IdImmediate imageOperand = { true, *(opIt++) };
3974 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003975 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003976 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3977 builder.setPrecision(result, precision);
3978 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003979 }
3980
John Kessenich149afc32018-08-14 13:31:43 -06003981 spv::IdImmediate coord = { true, *(opIt++) };
3982 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003983#ifdef AMD_EXTENSIONS
3984 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3985#else
John Kessenich56bab042015-09-16 10:54:31 -06003986 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003987#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003988 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003989 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003990 mask = mask | spv::ImageOperandsSampleMask;
3991 }
Rex Xu129799a2017-07-05 17:23:28 +08003992#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003993 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003994 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3995 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003996 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003997 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003998#endif
3999 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4000 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4001 if (mask) {
4002 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4003 operands.push_back(imageOperands);
4004 }
4005 if (mask & spv::ImageOperandsSampleMask) {
4006 spv::IdImmediate imageOperand = { true, *opIt++ };
4007 operands.push_back(imageOperand);
4008 }
4009#ifdef AMD_EXTENSIONS
4010 if (mask & spv::ImageOperandsLodMask) {
4011 spv::IdImmediate imageOperand = { true, *opIt++ };
4012 operands.push_back(imageOperand);
4013 }
4014#endif
4015 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4016 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4017 operands.push_back(imageOperand);
4018 }
4019
John Kessenich149afc32018-08-14 13:31:43 -06004020 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004021 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004022
John Kessenich149afc32018-08-14 13:31:43 -06004023 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004024 builder.setPrecision(result[0], precision);
4025
4026 // If needed, add a conversion constructor to the proper size.
4027 if (components != node->getType().getVectorSize())
4028 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4029
4030 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004031#ifdef AMD_EXTENSIONS
4032 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4033#else
John Kessenich56bab042015-09-16 10:54:31 -06004034 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004035#endif
Rex Xu129799a2017-07-05 17:23:28 +08004036
Jeff Bolz36831c92018-09-05 10:11:41 -05004037 // Push the texel value before the operands
4038#ifdef AMD_EXTENSIONS
4039 if (sampler.ms || cracked.lod) {
4040#else
4041 if (sampler.ms) {
4042#endif
John Kessenich149afc32018-08-14 13:31:43 -06004043 spv::IdImmediate texel = { true, *(opIt + 1) };
4044 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004045 } else {
4046 spv::IdImmediate texel = { true, *opIt };
4047 operands.push_back(texel);
4048 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004049
4050 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4051 if (sampler.ms) {
4052 mask = mask | spv::ImageOperandsSampleMask;
4053 }
4054#ifdef AMD_EXTENSIONS
4055 if (cracked.lod) {
4056 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4057 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4058 mask = mask | spv::ImageOperandsLodMask;
4059 }
4060#endif
4061 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4062 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4063 if (mask) {
4064 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4065 operands.push_back(imageOperands);
4066 }
4067 if (mask & spv::ImageOperandsSampleMask) {
4068 spv::IdImmediate imageOperand = { true, *opIt++ };
4069 operands.push_back(imageOperand);
4070 }
4071#ifdef AMD_EXTENSIONS
4072 if (mask & spv::ImageOperandsLodMask) {
4073 spv::IdImmediate imageOperand = { true, *opIt++ };
4074 operands.push_back(imageOperand);
4075 }
4076#endif
4077 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4078 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4079 operands.push_back(imageOperand);
4080 }
4081
John Kessenich56bab042015-09-16 10:54:31 -06004082 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004083 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004084 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004085 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004086#ifdef AMD_EXTENSIONS
4087 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4088#else
Rex Xu5eafa472016-02-19 22:24:03 +08004089 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004090#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004091 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004092 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004093 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4094
Jeff Bolz36831c92018-09-05 10:11:41 -05004095 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004096 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004097 mask = mask | spv::ImageOperandsSampleMask;
4098 }
Rex Xu129799a2017-07-05 17:23:28 +08004099#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004100 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004101 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4102 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4103
Jeff Bolz36831c92018-09-05 10:11:41 -05004104 mask = mask | spv::ImageOperandsLodMask;
4105 }
4106#endif
4107 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4108 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4109 if (mask) {
4110 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004111 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004112 }
4113 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004114 spv::IdImmediate imageOperand = { true, *opIt++ };
4115 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004116 }
4117#ifdef AMD_EXTENSIONS
4118 if (mask & spv::ImageOperandsLodMask) {
4119 spv::IdImmediate imageOperand = { true, *opIt++ };
4120 operands.push_back(imageOperand);
4121 }
Rex Xu129799a2017-07-05 17:23:28 +08004122#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004123 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4124 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4125 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004126 }
4127
4128 // Create the return type that was a special structure
4129 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004130 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004131 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4132 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4133
4134 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4135
4136 // Decode the return type
4137 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4138 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004139 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004140 // Process image atomic operations
4141
4142 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4143 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004144 // For non-MS, the sample value should be 0
4145 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4146 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004147
Jeff Bolz36831c92018-09-05 10:11:41 -05004148 spv::Id resultTypeId;
4149 // imageAtomicStore has a void return type so base the pointer type on
4150 // the type of the value operand.
4151 if (node->getOp() == glslang::EOpImageAtomicStore) {
4152 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4153 } else {
4154 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4155 }
John Kessenich56bab042015-09-16 10:54:31 -06004156 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004157
4158 std::vector<spv::Id> operands;
4159 operands.push_back(pointer);
4160 for (; opIt != arguments.end(); ++opIt)
4161 operands.push_back(*opIt);
4162
John Kessenich8c8505c2016-07-26 12:50:38 -06004163 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004164 }
4165 }
4166
amhagan05506bb2017-06-13 16:53:02 -04004167#ifdef AMD_EXTENSIONS
4168 // Check for fragment mask functions other than queries
4169 if (cracked.fragMask) {
4170 assert(sampler.ms);
4171
4172 auto opIt = arguments.begin();
4173 std::vector<spv::Id> operands;
4174
4175 // Extract the image if necessary
4176 if (builder.isSampledImage(params.sampler))
4177 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4178
4179 operands.push_back(params.sampler);
4180 ++opIt;
4181
4182 if (sampler.isSubpass()) {
4183 // add on the (0,0) coordinate
4184 spv::Id zero = builder.makeIntConstant(0);
4185 std::vector<spv::Id> comps;
4186 comps.push_back(zero);
4187 comps.push_back(zero);
4188 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4189 }
4190
4191 for (; opIt != arguments.end(); ++opIt)
4192 operands.push_back(*opIt);
4193
4194 spv::Op fragMaskOp = spv::OpNop;
4195 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4196 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4197 else if (node->getOp() == glslang::EOpFragmentFetch)
4198 fragMaskOp = spv::OpFragmentFetchAMD;
4199
4200 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4201 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4202 return builder.createOp(fragMaskOp, resultType(), operands);
4203 }
4204#endif
4205
Rex Xufc618912015-09-09 16:42:49 +08004206 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004207 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004208#ifdef NV_EXTENSIONS
4209 bool imageFootprint = node->isImageFootprint();
4210#endif
4211
Rex Xu71519fe2015-11-11 15:35:47 +08004212 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4213
John Kessenichfc51d282015-08-19 13:34:18 -06004214 // check for bias argument
4215 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004216#ifdef AMD_EXTENSIONS
4217 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4218#else
Rex Xu71519fe2015-11-11 15:35:47 +08004219 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004220#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004221 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004222#ifdef AMD_EXTENSIONS
4223 if (cracked.gather)
4224 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004225
4226 if (f16ShadowCompare)
4227 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004228#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004229 if (cracked.offset)
4230 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004231#ifdef AMD_EXTENSIONS
4232 else if (cracked.offsets)
4233 ++nonBiasArgCount;
4234#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004235 if (cracked.grad)
4236 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004237 if (cracked.lodClamp)
4238 ++nonBiasArgCount;
4239 if (sparse)
4240 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004241#ifdef NV_EXTENSIONS
4242 if (imageFootprint)
4243 //Following three extra arguments
4244 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4245 nonBiasArgCount += 3;
4246#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004247 if ((int)arguments.size() > nonBiasArgCount)
4248 bias = true;
4249 }
4250
John Kessenicha5c33d62016-06-02 23:45:21 -06004251 // See if the sampler param should really be just the SPV image part
4252 if (cracked.fetch) {
4253 // a fetch needs to have the image extracted first
4254 if (builder.isSampledImage(params.sampler))
4255 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4256 }
4257
Rex Xu225e0fc2016-11-17 17:47:59 +08004258#ifdef AMD_EXTENSIONS
4259 if (cracked.gather) {
4260 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4261 if (bias || cracked.lod ||
4262 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4263 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004264 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004265 }
4266 }
4267#endif
4268
John Kessenichfc51d282015-08-19 13:34:18 -06004269 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004270
John Kessenichfc51d282015-08-19 13:34:18 -06004271 params.coords = arguments[1];
4272 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004273 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004274
4275 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004276#ifdef AMD_EXTENSIONS
4277 if (cubeCompare || f16ShadowCompare) {
4278#else
Rex Xu48edadf2015-12-31 16:11:41 +08004279 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004280#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004281 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004282 ++extraArgs;
4283 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004284 params.Dref = arguments[2];
4285 ++extraArgs;
4286 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004287 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004288 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004289 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004290 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004291 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004292 dRefComp = builder.getNumComponents(params.coords) - 1;
4293 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004294 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4295 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004296
4297 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004298 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004299 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004300 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004301 } else if (glslangIntermediate->getStage() != EShLangFragment
4302#ifdef NV_EXTENSIONS
4303 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4304 && !(glslangIntermediate->getStage() == EShLangCompute &&
4305 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4306#endif
4307 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004308 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4309 noImplicitLod = true;
4310 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004311
4312 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004313 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004314 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004315 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004316 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004317
4318 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004319 if (cracked.grad) {
4320 params.gradX = arguments[2 + extraArgs];
4321 params.gradY = arguments[3 + extraArgs];
4322 extraArgs += 2;
4323 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004324
4325 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004326 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004327 params.offset = arguments[2 + extraArgs];
4328 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004329 } else if (cracked.offsets) {
4330 params.offsets = arguments[2 + extraArgs];
4331 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004332 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004333
4334 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004335 if (cracked.lodClamp) {
4336 params.lodClamp = arguments[2 + extraArgs];
4337 ++extraArgs;
4338 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004339 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004340 if (sparse) {
4341 params.texelOut = arguments[2 + extraArgs];
4342 ++extraArgs;
4343 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004344
John Kessenich76d4dfc2016-06-16 12:43:23 -06004345 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004346 if (cracked.gather && ! sampler.shadow) {
4347 // default component is 0, if missing, otherwise an argument
4348 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004349 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004350 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004351 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004352 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004353 }
Chao Chen3a137962018-09-19 11:41:27 -07004354#ifdef NV_EXTENSIONS
4355 spv::Id resultStruct = spv::NoResult;
4356 if (imageFootprint) {
4357 //Following three extra arguments
4358 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4359 params.granularity = arguments[2 + extraArgs];
4360 params.coarse = arguments[3 + extraArgs];
4361 resultStruct = arguments[4 + extraArgs];
4362 extraArgs += 3;
4363 }
4364#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004365 // bias
4366 if (bias) {
4367 params.bias = arguments[2 + extraArgs];
4368 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004369 }
John Kessenichfc51d282015-08-19 13:34:18 -06004370
Chao Chen3a137962018-09-19 11:41:27 -07004371#ifdef NV_EXTENSIONS
4372 if (imageFootprint) {
4373 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4374 builder.addCapability(spv::CapabilityImageFootprintNV);
4375
4376
4377 //resultStructType(OpenGL type) contains 5 elements:
4378 //struct gl_TextureFootprint2DNV {
4379 // uvec2 anchor;
4380 // uvec2 offset;
4381 // uvec2 mask;
4382 // uint lod;
4383 // uint granularity;
4384 //};
4385 //or
4386 //struct gl_TextureFootprint3DNV {
4387 // uvec3 anchor;
4388 // uvec3 offset;
4389 // uvec2 mask;
4390 // uint lod;
4391 // uint granularity;
4392 //};
4393 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4394 assert(builder.isStructType(resultStructType));
4395
4396 //resType (SPIR-V type) contains 6 elements:
4397 //Member 0 must be a Boolean type scalar(LOD),
4398 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4399 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4400 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4401 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4402 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4403 std::vector<spv::Id> members;
4404 members.push_back(resultType());
4405 for (int i = 0; i < 5; i++) {
4406 members.push_back(builder.getContainedTypeId(resultStructType, i));
4407 }
4408 spv::Id resType = builder.makeStructType(members, "ResType");
4409
4410 //call ImageFootprintNV
4411 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4412
4413 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4414 for (int i = 0; i < 5; i++) {
4415 builder.clearAccessChain();
4416 builder.setAccessChainLValue(resultStruct);
4417
4418 //Accessing to a struct we created, no coherent flag is set
4419 spv::Builder::AccessChain::CoherentFlags flags;
4420 flags.clear();
4421
4422 builder.accessChainPush(builder.makeIntConstant(i), flags);
4423 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4424 }
4425 return builder.createCompositeExtract(res, resultType(), 0);
4426 }
4427#endif
4428
John Kessenich65336482016-06-16 14:06:26 -06004429 // projective component (might not to move)
4430 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4431 // are divided by the last component of P."
4432 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4433 // unused components will appear after all used components."
4434 if (cracked.proj) {
4435 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4436 int projTargetComp;
4437 switch (sampler.dim) {
4438 case glslang::Esd1D: projTargetComp = 1; break;
4439 case glslang::Esd2D: projTargetComp = 2; break;
4440 case glslang::EsdRect: projTargetComp = 2; break;
4441 default: projTargetComp = projSourceComp; break;
4442 }
4443 // copy the projective coordinate if we have to
4444 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004445 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004446 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4447 projSourceComp);
4448 params.coords = builder.createCompositeInsert(projComp, params.coords,
4449 builder.getTypeId(params.coords), projTargetComp);
4450 }
4451 }
4452
Jeff Bolz36831c92018-09-05 10:11:41 -05004453 // nonprivate
4454 if (imageType.getQualifier().nonprivate) {
4455 params.nonprivate = true;
4456 }
4457
4458 // volatile
4459 if (imageType.getQualifier().volatil) {
4460 params.volatil = true;
4461 }
4462
St0fFa1184dd2018-04-09 21:08:14 +02004463 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004464 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004465 );
LoopDawg4425f242018-02-18 11:40:01 -07004466
4467 if (components != node->getType().getVectorSize())
4468 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4469
4470 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004471}
4472
4473spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4474{
4475 // Grab the function's pointer from the previously created function
4476 spv::Function* function = functionMap[node->getName().c_str()];
4477 if (! function)
4478 return 0;
4479
4480 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4481 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4482
4483 // See comments in makeFunctions() for details about the semantics for parameter passing.
4484 //
4485 // These imply we need a four step process:
4486 // 1. Evaluate the arguments
4487 // 2. Allocate and make copies of in, out, and inout arguments
4488 // 3. Make the call
4489 // 4. Copy back the results
4490
John Kessenichd3ed90b2018-05-04 11:43:03 -06004491 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004492 std::vector<spv::Builder::AccessChain> lValues;
4493 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004494 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004496 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004497 // build l-value
4498 builder.clearAccessChain();
4499 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004500 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004501 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004502 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004503 // save l-value
4504 lValues.push_back(builder.getAccessChain());
4505 } else {
4506 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004507 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004508 }
4509 }
4510
4511 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4512 // copy the original into that space.
4513 //
4514 // Also, build up the list of actual arguments to pass in for the call
4515 int lValueCount = 0;
4516 int rValueCount = 0;
4517 std::vector<spv::Id> spvArgs;
4518 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4519 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004520 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004521 builder.setAccessChain(lValues[lValueCount]);
4522 arg = builder.accessChainGetLValue();
4523 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004524 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004525 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004526 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004527 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4528 // need to copy the input into output space
4529 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004530 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004531 builder.clearAccessChain();
4532 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004533 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004534 }
4535 ++lValueCount;
4536 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004537 // process r-value, which involves a copy for a type mismatch
4538 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4539 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4540 builder.clearAccessChain();
4541 builder.setAccessChainLValue(argCopy);
4542 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4543 arg = builder.createLoad(argCopy);
4544 } else
4545 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004546 ++rValueCount;
4547 }
4548 spvArgs.push_back(arg);
4549 }
4550
4551 // 3. Make the call.
4552 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004553 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004554
4555 // 4. Copy back out an "out" arguments.
4556 lValueCount = 0;
4557 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004558 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004559 ++lValueCount;
4560 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004561 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4562 spv::Id copy = builder.createLoad(spvArgs[a]);
4563 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004564 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 }
4566 ++lValueCount;
4567 }
4568 }
4569
4570 return result;
4571}
4572
4573// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004574spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004575 spv::Id typeId, spv::Id left, spv::Id right,
4576 glslang::TBasicType typeProxy, bool reduceComparison)
4577{
John Kessenich66011cb2018-03-06 16:12:04 -07004578 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4579 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004580 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004581
4582 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004583 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004584 bool comparison = false;
4585
4586 switch (op) {
4587 case glslang::EOpAdd:
4588 case glslang::EOpAddAssign:
4589 if (isFloat)
4590 binOp = spv::OpFAdd;
4591 else
4592 binOp = spv::OpIAdd;
4593 break;
4594 case glslang::EOpSub:
4595 case glslang::EOpSubAssign:
4596 if (isFloat)
4597 binOp = spv::OpFSub;
4598 else
4599 binOp = spv::OpISub;
4600 break;
4601 case glslang::EOpMul:
4602 case glslang::EOpMulAssign:
4603 if (isFloat)
4604 binOp = spv::OpFMul;
4605 else
4606 binOp = spv::OpIMul;
4607 break;
4608 case glslang::EOpVectorTimesScalar:
4609 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004610 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004611 if (builder.isVector(right))
4612 std::swap(left, right);
4613 assert(builder.isScalar(right));
4614 needMatchingVectors = false;
4615 binOp = spv::OpVectorTimesScalar;
4616 } else
4617 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004618 break;
4619 case glslang::EOpVectorTimesMatrix:
4620 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004621 binOp = spv::OpVectorTimesMatrix;
4622 break;
4623 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004624 binOp = spv::OpMatrixTimesVector;
4625 break;
4626 case glslang::EOpMatrixTimesScalar:
4627 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004628 binOp = spv::OpMatrixTimesScalar;
4629 break;
4630 case glslang::EOpMatrixTimesMatrix:
4631 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004632 binOp = spv::OpMatrixTimesMatrix;
4633 break;
4634 case glslang::EOpOuterProduct:
4635 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004636 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004637 break;
4638
4639 case glslang::EOpDiv:
4640 case glslang::EOpDivAssign:
4641 if (isFloat)
4642 binOp = spv::OpFDiv;
4643 else if (isUnsigned)
4644 binOp = spv::OpUDiv;
4645 else
4646 binOp = spv::OpSDiv;
4647 break;
4648 case glslang::EOpMod:
4649 case glslang::EOpModAssign:
4650 if (isFloat)
4651 binOp = spv::OpFMod;
4652 else if (isUnsigned)
4653 binOp = spv::OpUMod;
4654 else
4655 binOp = spv::OpSMod;
4656 break;
4657 case glslang::EOpRightShift:
4658 case glslang::EOpRightShiftAssign:
4659 if (isUnsigned)
4660 binOp = spv::OpShiftRightLogical;
4661 else
4662 binOp = spv::OpShiftRightArithmetic;
4663 break;
4664 case glslang::EOpLeftShift:
4665 case glslang::EOpLeftShiftAssign:
4666 binOp = spv::OpShiftLeftLogical;
4667 break;
4668 case glslang::EOpAnd:
4669 case glslang::EOpAndAssign:
4670 binOp = spv::OpBitwiseAnd;
4671 break;
4672 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004673 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004674 binOp = spv::OpLogicalAnd;
4675 break;
4676 case glslang::EOpInclusiveOr:
4677 case glslang::EOpInclusiveOrAssign:
4678 binOp = spv::OpBitwiseOr;
4679 break;
4680 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004681 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004682 binOp = spv::OpLogicalOr;
4683 break;
4684 case glslang::EOpExclusiveOr:
4685 case glslang::EOpExclusiveOrAssign:
4686 binOp = spv::OpBitwiseXor;
4687 break;
4688 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004689 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004690 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004691 break;
4692
4693 case glslang::EOpLessThan:
4694 case glslang::EOpGreaterThan:
4695 case glslang::EOpLessThanEqual:
4696 case glslang::EOpGreaterThanEqual:
4697 case glslang::EOpEqual:
4698 case glslang::EOpNotEqual:
4699 case glslang::EOpVectorEqual:
4700 case glslang::EOpVectorNotEqual:
4701 comparison = true;
4702 break;
4703 default:
4704 break;
4705 }
4706
John Kessenich7c1aa102015-10-15 13:29:11 -06004707 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004708 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004709 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004710 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004711 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004712
4713 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004714 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004715 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004716
qining25262b32016-05-06 17:25:16 -04004717 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004718 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004719 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004720 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004721 }
4722
4723 if (! comparison)
4724 return 0;
4725
John Kessenich7c1aa102015-10-15 13:29:11 -06004726 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004727
John Kessenich4583b612016-08-07 19:14:22 -06004728 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004729 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4730 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004731 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004732 return result;
4733 }
John Kessenich140f3df2015-06-26 16:58:36 -06004734
4735 switch (op) {
4736 case glslang::EOpLessThan:
4737 if (isFloat)
4738 binOp = spv::OpFOrdLessThan;
4739 else if (isUnsigned)
4740 binOp = spv::OpULessThan;
4741 else
4742 binOp = spv::OpSLessThan;
4743 break;
4744 case glslang::EOpGreaterThan:
4745 if (isFloat)
4746 binOp = spv::OpFOrdGreaterThan;
4747 else if (isUnsigned)
4748 binOp = spv::OpUGreaterThan;
4749 else
4750 binOp = spv::OpSGreaterThan;
4751 break;
4752 case glslang::EOpLessThanEqual:
4753 if (isFloat)
4754 binOp = spv::OpFOrdLessThanEqual;
4755 else if (isUnsigned)
4756 binOp = spv::OpULessThanEqual;
4757 else
4758 binOp = spv::OpSLessThanEqual;
4759 break;
4760 case glslang::EOpGreaterThanEqual:
4761 if (isFloat)
4762 binOp = spv::OpFOrdGreaterThanEqual;
4763 else if (isUnsigned)
4764 binOp = spv::OpUGreaterThanEqual;
4765 else
4766 binOp = spv::OpSGreaterThanEqual;
4767 break;
4768 case glslang::EOpEqual:
4769 case glslang::EOpVectorEqual:
4770 if (isFloat)
4771 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004772 else if (isBool)
4773 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004774 else
4775 binOp = spv::OpIEqual;
4776 break;
4777 case glslang::EOpNotEqual:
4778 case glslang::EOpVectorNotEqual:
4779 if (isFloat)
4780 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004781 else if (isBool)
4782 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004783 else
4784 binOp = spv::OpINotEqual;
4785 break;
4786 default:
4787 break;
4788 }
4789
qining25262b32016-05-06 17:25:16 -04004790 if (binOp != spv::OpNop) {
4791 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004792 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004793 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004794 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004795 }
John Kessenich140f3df2015-06-26 16:58:36 -06004796
4797 return 0;
4798}
4799
John Kessenich04bb8a02015-12-12 12:28:14 -07004800//
4801// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4802// These can be any of:
4803//
4804// matrix * scalar
4805// scalar * matrix
4806// matrix * matrix linear algebraic
4807// matrix * vector
4808// vector * matrix
4809// matrix * matrix componentwise
4810// matrix op matrix op in {+, -, /}
4811// matrix op scalar op in {+, -, /}
4812// scalar op matrix op in {+, -, /}
4813//
John Kessenichead86222018-03-28 18:01:20 -06004814spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4815 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004816{
4817 bool firstClass = true;
4818
4819 // First, handle first-class matrix operations (* and matrix/scalar)
4820 switch (op) {
4821 case spv::OpFDiv:
4822 if (builder.isMatrix(left) && builder.isScalar(right)) {
4823 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004824 spv::Id resultType = builder.getTypeId(right);
4825 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004826 op = spv::OpMatrixTimesScalar;
4827 } else
4828 firstClass = false;
4829 break;
4830 case spv::OpMatrixTimesScalar:
4831 if (builder.isMatrix(right))
4832 std::swap(left, right);
4833 assert(builder.isScalar(right));
4834 break;
4835 case spv::OpVectorTimesMatrix:
4836 assert(builder.isVector(left));
4837 assert(builder.isMatrix(right));
4838 break;
4839 case spv::OpMatrixTimesVector:
4840 assert(builder.isMatrix(left));
4841 assert(builder.isVector(right));
4842 break;
4843 case spv::OpMatrixTimesMatrix:
4844 assert(builder.isMatrix(left));
4845 assert(builder.isMatrix(right));
4846 break;
4847 default:
4848 firstClass = false;
4849 break;
4850 }
4851
qining25262b32016-05-06 17:25:16 -04004852 if (firstClass) {
4853 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004854 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004855 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004856 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004857 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004858
LoopDawg592860c2016-06-09 08:57:35 -06004859 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004860 // The result type of all of them is the same type as the (a) matrix operand.
4861 // The algorithm is to:
4862 // - break the matrix(es) into vectors
4863 // - smear any scalar to a vector
4864 // - do vector operations
4865 // - make a matrix out the vector results
4866 switch (op) {
4867 case spv::OpFAdd:
4868 case spv::OpFSub:
4869 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004870 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004871 case spv::OpFMul:
4872 {
4873 // one time set up...
4874 bool leftMat = builder.isMatrix(left);
4875 bool rightMat = builder.isMatrix(right);
4876 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4877 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4878 spv::Id scalarType = builder.getScalarTypeId(typeId);
4879 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4880 std::vector<spv::Id> results;
4881 spv::Id smearVec = spv::NoResult;
4882 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004883 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004884 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004885 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004886
4887 // do each vector op
4888 for (unsigned int c = 0; c < numCols; ++c) {
4889 std::vector<unsigned int> indexes;
4890 indexes.push_back(c);
4891 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4892 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004893 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004894 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004895 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004896 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004897 }
4898
4899 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004900 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004901 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004902 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004903 }
4904 default:
4905 assert(0);
4906 return spv::NoResult;
4907 }
4908}
4909
John Kessenichead86222018-03-28 18:01:20 -06004910spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4911 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004912{
4913 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004914 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004915 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004916 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4917 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004918
4919 switch (op) {
4920 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004921 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004922 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004923 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004924 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004925 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004926 unaryOp = spv::OpSNegate;
4927 break;
4928
4929 case glslang::EOpLogicalNot:
4930 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004931 unaryOp = spv::OpLogicalNot;
4932 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004933 case glslang::EOpBitwiseNot:
4934 unaryOp = spv::OpNot;
4935 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004936
John Kessenich140f3df2015-06-26 16:58:36 -06004937 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004938 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004939 break;
4940 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004941 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004942 break;
4943 case glslang::EOpTranspose:
4944 unaryOp = spv::OpTranspose;
4945 break;
4946
4947 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004948 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 break;
4950 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004951 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004952 break;
4953 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004954 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004955 break;
4956 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004957 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004958 break;
4959 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004960 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004961 break;
4962 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004963 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004964 break;
4965 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004966 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004967 break;
4968 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004969 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004970 break;
4971
4972 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004973 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004974 break;
4975 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004976 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004977 break;
4978 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004979 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
4981 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004983 break;
4984 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004985 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004986 break;
4987 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004988 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 break;
4990
4991 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004992 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004993 break;
4994 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004995 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004996 break;
4997
4998 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004999 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
5004 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005005 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005006 break;
5007 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005008 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005009 break;
5010 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005011 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005012 break;
5013 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005014 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005015 break;
5016
5017 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005018 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005019 break;
5020 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005022 break;
5023 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005024 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005025 break;
5026 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005027 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005028 break;
5029 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005030 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005031 break;
5032 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005033 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005034 break;
5035
5036 case glslang::EOpIsNan:
5037 unaryOp = spv::OpIsNan;
5038 break;
5039 case glslang::EOpIsInf:
5040 unaryOp = spv::OpIsInf;
5041 break;
LoopDawg592860c2016-06-09 08:57:35 -06005042 case glslang::EOpIsFinite:
5043 unaryOp = spv::OpIsFinite;
5044 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005045
Rex Xucbc426e2015-12-15 16:03:10 +08005046 case glslang::EOpFloatBitsToInt:
5047 case glslang::EOpFloatBitsToUint:
5048 case glslang::EOpIntBitsToFloat:
5049 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005050 case glslang::EOpDoubleBitsToInt64:
5051 case glslang::EOpDoubleBitsToUint64:
5052 case glslang::EOpInt64BitsToDouble:
5053 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005054 case glslang::EOpFloat16BitsToInt16:
5055 case glslang::EOpFloat16BitsToUint16:
5056 case glslang::EOpInt16BitsToFloat16:
5057 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005058 unaryOp = spv::OpBitcast;
5059 break;
5060
John Kessenich140f3df2015-06-26 16:58:36 -06005061 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005062 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005063 break;
5064 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005065 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005066 break;
5067 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005068 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005069 break;
5070 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005071 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005072 break;
5073 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005074 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005075 break;
5076 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005077 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005078 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005079 case glslang::EOpPackSnorm4x8:
5080 libCall = spv::GLSLstd450PackSnorm4x8;
5081 break;
5082 case glslang::EOpUnpackSnorm4x8:
5083 libCall = spv::GLSLstd450UnpackSnorm4x8;
5084 break;
5085 case glslang::EOpPackUnorm4x8:
5086 libCall = spv::GLSLstd450PackUnorm4x8;
5087 break;
5088 case glslang::EOpUnpackUnorm4x8:
5089 libCall = spv::GLSLstd450UnpackUnorm4x8;
5090 break;
5091 case glslang::EOpPackDouble2x32:
5092 libCall = spv::GLSLstd450PackDouble2x32;
5093 break;
5094 case glslang::EOpUnpackDouble2x32:
5095 libCall = spv::GLSLstd450UnpackDouble2x32;
5096 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005097
Rex Xu8ff43de2016-04-22 16:51:45 +08005098 case glslang::EOpPackInt2x32:
5099 case glslang::EOpUnpackInt2x32:
5100 case glslang::EOpPackUint2x32:
5101 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005102 case glslang::EOpPack16:
5103 case glslang::EOpPack32:
5104 case glslang::EOpPack64:
5105 case glslang::EOpUnpack32:
5106 case glslang::EOpUnpack16:
5107 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005108 case glslang::EOpPackInt2x16:
5109 case glslang::EOpUnpackInt2x16:
5110 case glslang::EOpPackUint2x16:
5111 case glslang::EOpUnpackUint2x16:
5112 case glslang::EOpPackInt4x16:
5113 case glslang::EOpUnpackInt4x16:
5114 case glslang::EOpPackUint4x16:
5115 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005116 case glslang::EOpPackFloat2x16:
5117 case glslang::EOpUnpackFloat2x16:
5118 unaryOp = spv::OpBitcast;
5119 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005120
John Kessenich140f3df2015-06-26 16:58:36 -06005121 case glslang::EOpDPdx:
5122 unaryOp = spv::OpDPdx;
5123 break;
5124 case glslang::EOpDPdy:
5125 unaryOp = spv::OpDPdy;
5126 break;
5127 case glslang::EOpFwidth:
5128 unaryOp = spv::OpFwidth;
5129 break;
5130 case glslang::EOpDPdxFine:
5131 unaryOp = spv::OpDPdxFine;
5132 break;
5133 case glslang::EOpDPdyFine:
5134 unaryOp = spv::OpDPdyFine;
5135 break;
5136 case glslang::EOpFwidthFine:
5137 unaryOp = spv::OpFwidthFine;
5138 break;
5139 case glslang::EOpDPdxCoarse:
5140 unaryOp = spv::OpDPdxCoarse;
5141 break;
5142 case glslang::EOpDPdyCoarse:
5143 unaryOp = spv::OpDPdyCoarse;
5144 break;
5145 case glslang::EOpFwidthCoarse:
5146 unaryOp = spv::OpFwidthCoarse;
5147 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005148 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005149#ifdef AMD_EXTENSIONS
5150 if (typeProxy == glslang::EbtFloat16)
5151 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5152#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005153 libCall = spv::GLSLstd450InterpolateAtCentroid;
5154 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005155 case glslang::EOpAny:
5156 unaryOp = spv::OpAny;
5157 break;
5158 case glslang::EOpAll:
5159 unaryOp = spv::OpAll;
5160 break;
5161
5162 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005163 if (isFloat)
5164 libCall = spv::GLSLstd450FAbs;
5165 else
5166 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005169 if (isFloat)
5170 libCall = spv::GLSLstd450FSign;
5171 else
5172 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005173 break;
5174
John Kessenichfc51d282015-08-19 13:34:18 -06005175 case glslang::EOpAtomicCounterIncrement:
5176 case glslang::EOpAtomicCounterDecrement:
5177 case glslang::EOpAtomicCounter:
5178 {
5179 // Handle all of the atomics in one place, in createAtomicOperation()
5180 std::vector<spv::Id> operands;
5181 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005182 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005183 }
5184
John Kessenichfc51d282015-08-19 13:34:18 -06005185 case glslang::EOpBitFieldReverse:
5186 unaryOp = spv::OpBitReverse;
5187 break;
5188 case glslang::EOpBitCount:
5189 unaryOp = spv::OpBitCount;
5190 break;
5191 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005192 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005193 break;
5194 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005195 if (isUnsigned)
5196 libCall = spv::GLSLstd450FindUMsb;
5197 else
5198 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005199 break;
5200
Rex Xu574ab042016-04-14 16:53:07 +08005201 case glslang::EOpBallot:
5202 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005203 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005204 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005205 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005206#ifdef AMD_EXTENSIONS
5207 case glslang::EOpMinInvocations:
5208 case glslang::EOpMaxInvocations:
5209 case glslang::EOpAddInvocations:
5210 case glslang::EOpMinInvocationsNonUniform:
5211 case glslang::EOpMaxInvocationsNonUniform:
5212 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005213 case glslang::EOpMinInvocationsInclusiveScan:
5214 case glslang::EOpMaxInvocationsInclusiveScan:
5215 case glslang::EOpAddInvocationsInclusiveScan:
5216 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5217 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5218 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5219 case glslang::EOpMinInvocationsExclusiveScan:
5220 case glslang::EOpMaxInvocationsExclusiveScan:
5221 case glslang::EOpAddInvocationsExclusiveScan:
5222 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5223 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5224 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005225#endif
Rex Xu51596642016-09-21 18:56:12 +08005226 {
5227 std::vector<spv::Id> operands;
5228 operands.push_back(operand);
5229 return createInvocationsOperation(op, typeId, operands, typeProxy);
5230 }
John Kessenich66011cb2018-03-06 16:12:04 -07005231 case glslang::EOpSubgroupAll:
5232 case glslang::EOpSubgroupAny:
5233 case glslang::EOpSubgroupAllEqual:
5234 case glslang::EOpSubgroupBroadcastFirst:
5235 case glslang::EOpSubgroupBallot:
5236 case glslang::EOpSubgroupInverseBallot:
5237 case glslang::EOpSubgroupBallotBitCount:
5238 case glslang::EOpSubgroupBallotInclusiveBitCount:
5239 case glslang::EOpSubgroupBallotExclusiveBitCount:
5240 case glslang::EOpSubgroupBallotFindLSB:
5241 case glslang::EOpSubgroupBallotFindMSB:
5242 case glslang::EOpSubgroupAdd:
5243 case glslang::EOpSubgroupMul:
5244 case glslang::EOpSubgroupMin:
5245 case glslang::EOpSubgroupMax:
5246 case glslang::EOpSubgroupAnd:
5247 case glslang::EOpSubgroupOr:
5248 case glslang::EOpSubgroupXor:
5249 case glslang::EOpSubgroupInclusiveAdd:
5250 case glslang::EOpSubgroupInclusiveMul:
5251 case glslang::EOpSubgroupInclusiveMin:
5252 case glslang::EOpSubgroupInclusiveMax:
5253 case glslang::EOpSubgroupInclusiveAnd:
5254 case glslang::EOpSubgroupInclusiveOr:
5255 case glslang::EOpSubgroupInclusiveXor:
5256 case glslang::EOpSubgroupExclusiveAdd:
5257 case glslang::EOpSubgroupExclusiveMul:
5258 case glslang::EOpSubgroupExclusiveMin:
5259 case glslang::EOpSubgroupExclusiveMax:
5260 case glslang::EOpSubgroupExclusiveAnd:
5261 case glslang::EOpSubgroupExclusiveOr:
5262 case glslang::EOpSubgroupExclusiveXor:
5263 case glslang::EOpSubgroupQuadSwapHorizontal:
5264 case glslang::EOpSubgroupQuadSwapVertical:
5265 case glslang::EOpSubgroupQuadSwapDiagonal: {
5266 std::vector<spv::Id> operands;
5267 operands.push_back(operand);
5268 return createSubgroupOperation(op, typeId, operands, typeProxy);
5269 }
Rex Xu9d93a232016-05-05 12:30:44 +08005270#ifdef AMD_EXTENSIONS
5271 case glslang::EOpMbcnt:
5272 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5273 libCall = spv::MbcntAMD;
5274 break;
5275
5276 case glslang::EOpCubeFaceIndex:
5277 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5278 libCall = spv::CubeFaceIndexAMD;
5279 break;
5280
5281 case glslang::EOpCubeFaceCoord:
5282 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5283 libCall = spv::CubeFaceCoordAMD;
5284 break;
5285#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005286#ifdef NV_EXTENSIONS
5287 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005288 unaryOp = spv::OpGroupNonUniformPartitionNV;
5289 break;
5290#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005291 default:
5292 return 0;
5293 }
5294
5295 spv::Id id;
5296 if (libCall >= 0) {
5297 std::vector<spv::Id> args;
5298 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005299 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005300 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005301 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005302 }
John Kessenich140f3df2015-06-26 16:58:36 -06005303
John Kessenichead86222018-03-28 18:01:20 -06005304 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005305 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005306 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005307}
5308
John Kessenich7a53f762016-01-20 11:19:27 -07005309// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005310spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5311 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005312{
5313 // Handle unary operations vector by vector.
5314 // The result type is the same type as the original type.
5315 // The algorithm is to:
5316 // - break the matrix into vectors
5317 // - apply the operation to each vector
5318 // - make a matrix out the vector results
5319
5320 // get the types sorted out
5321 int numCols = builder.getNumColumns(operand);
5322 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005323 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5324 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005325 std::vector<spv::Id> results;
5326
5327 // do each vector op
5328 for (int c = 0; c < numCols; ++c) {
5329 std::vector<unsigned int> indexes;
5330 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005331 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5332 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005333 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005334 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005335 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005336 }
5337
5338 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005339 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005340 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005341 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005342}
5343
John Kessenichad7645f2018-06-04 19:11:25 -06005344// For converting integers where both the bitwidth and the signedness could
5345// change, but only do the width change here. The caller is still responsible
5346// for the signedness conversion.
5347spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005348{
John Kessenichad7645f2018-06-04 19:11:25 -06005349 // Get the result type width, based on the type to convert to.
5350 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005351 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005352 case glslang::EOpConvInt16ToUint8:
5353 case glslang::EOpConvIntToUint8:
5354 case glslang::EOpConvInt64ToUint8:
5355 case glslang::EOpConvUint16ToInt8:
5356 case glslang::EOpConvUintToInt8:
5357 case glslang::EOpConvUint64ToInt8:
5358 width = 8;
5359 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005360 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005361 case glslang::EOpConvIntToUint16:
5362 case glslang::EOpConvInt64ToUint16:
5363 case glslang::EOpConvUint8ToInt16:
5364 case glslang::EOpConvUintToInt16:
5365 case glslang::EOpConvUint64ToInt16:
5366 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005367 break;
5368 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005369 case glslang::EOpConvInt16ToUint:
5370 case glslang::EOpConvInt64ToUint:
5371 case glslang::EOpConvUint8ToInt:
5372 case glslang::EOpConvUint16ToInt:
5373 case glslang::EOpConvUint64ToInt:
5374 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005375 break;
5376 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005377 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005378 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005379 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005380 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005381 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005382 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005383 break;
5384
5385 default:
5386 assert(false && "Default missing");
5387 break;
5388 }
5389
John Kessenichad7645f2018-06-04 19:11:25 -06005390 // Get the conversion operation and result type,
5391 // based on the target width, but the source type.
5392 spv::Id type = spv::NoType;
5393 spv::Op convOp = spv::OpNop;
5394 switch(op) {
5395 case glslang::EOpConvInt8ToUint16:
5396 case glslang::EOpConvInt8ToUint:
5397 case glslang::EOpConvInt8ToUint64:
5398 case glslang::EOpConvInt16ToUint8:
5399 case glslang::EOpConvInt16ToUint:
5400 case glslang::EOpConvInt16ToUint64:
5401 case glslang::EOpConvIntToUint8:
5402 case glslang::EOpConvIntToUint16:
5403 case glslang::EOpConvIntToUint64:
5404 case glslang::EOpConvInt64ToUint8:
5405 case glslang::EOpConvInt64ToUint16:
5406 case glslang::EOpConvInt64ToUint:
5407 convOp = spv::OpSConvert;
5408 type = builder.makeIntType(width);
5409 break;
5410 default:
5411 convOp = spv::OpUConvert;
5412 type = builder.makeUintType(width);
5413 break;
5414 }
5415
John Kessenich66011cb2018-03-06 16:12:04 -07005416 if (vectorSize > 0)
5417 type = builder.makeVectorType(type, vectorSize);
5418
John Kessenichad7645f2018-06-04 19:11:25 -06005419 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005420}
5421
John Kessenichead86222018-03-28 18:01:20 -06005422spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5423 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005424{
5425 spv::Op convOp = spv::OpNop;
5426 spv::Id zero = 0;
5427 spv::Id one = 0;
5428
5429 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5430
5431 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005432 case glslang::EOpConvInt8ToBool:
5433 case glslang::EOpConvUint8ToBool:
5434 zero = builder.makeUint8Constant(0);
5435 zero = makeSmearedConstant(zero, vectorSize);
5436 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005437 case glslang::EOpConvInt16ToBool:
5438 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005439 zero = builder.makeUint16Constant(0);
5440 zero = makeSmearedConstant(zero, vectorSize);
5441 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5442 case glslang::EOpConvIntToBool:
5443 case glslang::EOpConvUintToBool:
5444 zero = builder.makeUintConstant(0);
5445 zero = makeSmearedConstant(zero, vectorSize);
5446 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5447 case glslang::EOpConvInt64ToBool:
5448 case glslang::EOpConvUint64ToBool:
5449 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005450 zero = makeSmearedConstant(zero, vectorSize);
5451 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5452
5453 case glslang::EOpConvFloatToBool:
5454 zero = builder.makeFloatConstant(0.0F);
5455 zero = makeSmearedConstant(zero, vectorSize);
5456 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5457
5458 case glslang::EOpConvDoubleToBool:
5459 zero = builder.makeDoubleConstant(0.0);
5460 zero = makeSmearedConstant(zero, vectorSize);
5461 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5462
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005463 case glslang::EOpConvFloat16ToBool:
5464 zero = builder.makeFloat16Constant(0.0F);
5465 zero = makeSmearedConstant(zero, vectorSize);
5466 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005467
John Kessenich140f3df2015-06-26 16:58:36 -06005468 case glslang::EOpConvBoolToFloat:
5469 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005470 zero = builder.makeFloatConstant(0.0F);
5471 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005472 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005473
John Kessenich140f3df2015-06-26 16:58:36 -06005474 case glslang::EOpConvBoolToDouble:
5475 convOp = spv::OpSelect;
5476 zero = builder.makeDoubleConstant(0.0);
5477 one = builder.makeDoubleConstant(1.0);
5478 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005479
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005480 case glslang::EOpConvBoolToFloat16:
5481 convOp = spv::OpSelect;
5482 zero = builder.makeFloat16Constant(0.0F);
5483 one = builder.makeFloat16Constant(1.0F);
5484 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005485
5486 case glslang::EOpConvBoolToInt8:
5487 zero = builder.makeInt8Constant(0);
5488 one = builder.makeInt8Constant(1);
5489 convOp = spv::OpSelect;
5490 break;
5491
5492 case glslang::EOpConvBoolToUint8:
5493 zero = builder.makeUint8Constant(0);
5494 one = builder.makeUint8Constant(1);
5495 convOp = spv::OpSelect;
5496 break;
5497
5498 case glslang::EOpConvBoolToInt16:
5499 zero = builder.makeInt16Constant(0);
5500 one = builder.makeInt16Constant(1);
5501 convOp = spv::OpSelect;
5502 break;
5503
5504 case glslang::EOpConvBoolToUint16:
5505 zero = builder.makeUint16Constant(0);
5506 one = builder.makeUint16Constant(1);
5507 convOp = spv::OpSelect;
5508 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005509
John Kessenich140f3df2015-06-26 16:58:36 -06005510 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005511 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005512 if (op == glslang::EOpConvBoolToInt64)
5513 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005514 else
5515 zero = builder.makeIntConstant(0);
5516
5517 if (op == glslang::EOpConvBoolToInt64)
5518 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005519 else
5520 one = builder.makeIntConstant(1);
5521
John Kessenich140f3df2015-06-26 16:58:36 -06005522 convOp = spv::OpSelect;
5523 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005524
John Kessenich140f3df2015-06-26 16:58:36 -06005525 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005526 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005527 if (op == glslang::EOpConvBoolToUint64)
5528 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005529 else
5530 zero = builder.makeUintConstant(0);
5531
5532 if (op == glslang::EOpConvBoolToUint64)
5533 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005534 else
5535 one = builder.makeUintConstant(1);
5536
John Kessenich140f3df2015-06-26 16:58:36 -06005537 convOp = spv::OpSelect;
5538 break;
5539
John Kessenich66011cb2018-03-06 16:12:04 -07005540 case glslang::EOpConvInt8ToFloat16:
5541 case glslang::EOpConvInt8ToFloat:
5542 case glslang::EOpConvInt8ToDouble:
5543 case glslang::EOpConvInt16ToFloat16:
5544 case glslang::EOpConvInt16ToFloat:
5545 case glslang::EOpConvInt16ToDouble:
5546 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005547 case glslang::EOpConvIntToFloat:
5548 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005549 case glslang::EOpConvInt64ToFloat:
5550 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005551 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005552 convOp = spv::OpConvertSToF;
5553 break;
5554
John Kessenich66011cb2018-03-06 16:12:04 -07005555 case glslang::EOpConvUint8ToFloat16:
5556 case glslang::EOpConvUint8ToFloat:
5557 case glslang::EOpConvUint8ToDouble:
5558 case glslang::EOpConvUint16ToFloat16:
5559 case glslang::EOpConvUint16ToFloat:
5560 case glslang::EOpConvUint16ToDouble:
5561 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005562 case glslang::EOpConvUintToFloat:
5563 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005564 case glslang::EOpConvUint64ToFloat:
5565 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005566 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005567 convOp = spv::OpConvertUToF;
5568 break;
5569
5570 case glslang::EOpConvDoubleToFloat:
5571 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005572 case glslang::EOpConvDoubleToFloat16:
5573 case glslang::EOpConvFloat16ToDouble:
5574 case glslang::EOpConvFloatToFloat16:
5575 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005576 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005577 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005578 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005579 break;
5580
John Kessenich66011cb2018-03-06 16:12:04 -07005581 case glslang::EOpConvFloat16ToInt8:
5582 case glslang::EOpConvFloatToInt8:
5583 case glslang::EOpConvDoubleToInt8:
5584 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005585 case glslang::EOpConvFloatToInt16:
5586 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005587 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005588 case glslang::EOpConvFloatToInt:
5589 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005590 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005591 case glslang::EOpConvFloatToInt64:
5592 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005593 convOp = spv::OpConvertFToS;
5594 break;
5595
John Kessenich66011cb2018-03-06 16:12:04 -07005596 case glslang::EOpConvUint8ToInt8:
5597 case glslang::EOpConvInt8ToUint8:
5598 case glslang::EOpConvUint16ToInt16:
5599 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005600 case glslang::EOpConvUintToInt:
5601 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005602 case glslang::EOpConvUint64ToInt64:
5603 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005604 if (builder.isInSpecConstCodeGenMode()) {
5605 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005606 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5607 zero = builder.makeUint8Constant(0);
5608 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005609 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005610 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5611 zero = builder.makeUint64Constant(0);
5612 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005613 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005614 }
qining189b2032016-04-12 23:16:20 -04005615 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005616 // Use OpIAdd, instead of OpBitcast to do the conversion when
5617 // generating for OpSpecConstantOp instruction.
5618 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5619 }
5620 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005621 convOp = spv::OpBitcast;
5622 break;
5623
John Kessenich66011cb2018-03-06 16:12:04 -07005624 case glslang::EOpConvFloat16ToUint8:
5625 case glslang::EOpConvFloatToUint8:
5626 case glslang::EOpConvDoubleToUint8:
5627 case glslang::EOpConvFloat16ToUint16:
5628 case glslang::EOpConvFloatToUint16:
5629 case glslang::EOpConvDoubleToUint16:
5630 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005631 case glslang::EOpConvFloatToUint:
5632 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005633 case glslang::EOpConvFloatToUint64:
5634 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005635 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005636 convOp = spv::OpConvertFToU;
5637 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005638
John Kessenich66011cb2018-03-06 16:12:04 -07005639 case glslang::EOpConvInt8ToInt16:
5640 case glslang::EOpConvInt8ToInt:
5641 case glslang::EOpConvInt8ToInt64:
5642 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005643 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005644 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005645 case glslang::EOpConvIntToInt8:
5646 case glslang::EOpConvIntToInt16:
5647 case glslang::EOpConvIntToInt64:
5648 case glslang::EOpConvInt64ToInt8:
5649 case glslang::EOpConvInt64ToInt16:
5650 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005651 convOp = spv::OpSConvert;
5652 break;
5653
John Kessenich66011cb2018-03-06 16:12:04 -07005654 case glslang::EOpConvUint8ToUint16:
5655 case glslang::EOpConvUint8ToUint:
5656 case glslang::EOpConvUint8ToUint64:
5657 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005658 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005659 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005660 case glslang::EOpConvUintToUint8:
5661 case glslang::EOpConvUintToUint16:
5662 case glslang::EOpConvUintToUint64:
5663 case glslang::EOpConvUint64ToUint8:
5664 case glslang::EOpConvUint64ToUint16:
5665 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005666 convOp = spv::OpUConvert;
5667 break;
5668
John Kessenich66011cb2018-03-06 16:12:04 -07005669 case glslang::EOpConvInt8ToUint16:
5670 case glslang::EOpConvInt8ToUint:
5671 case glslang::EOpConvInt8ToUint64:
5672 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005673 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005674 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005675 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005676 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005677 case glslang::EOpConvIntToUint64:
5678 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005679 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005680 case glslang::EOpConvInt64ToUint:
5681 case glslang::EOpConvUint8ToInt16:
5682 case glslang::EOpConvUint8ToInt:
5683 case glslang::EOpConvUint8ToInt64:
5684 case glslang::EOpConvUint16ToInt8:
5685 case glslang::EOpConvUint16ToInt:
5686 case glslang::EOpConvUint16ToInt64:
5687 case glslang::EOpConvUintToInt8:
5688 case glslang::EOpConvUintToInt16:
5689 case glslang::EOpConvUintToInt64:
5690 case glslang::EOpConvUint64ToInt8:
5691 case glslang::EOpConvUint64ToInt16:
5692 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005693 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005694 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005695
5696 if (builder.isInSpecConstCodeGenMode()) {
5697 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005698 switch(op) {
5699 case glslang::EOpConvInt16ToUint8:
5700 case glslang::EOpConvIntToUint8:
5701 case glslang::EOpConvInt64ToUint8:
5702 case glslang::EOpConvUint16ToInt8:
5703 case glslang::EOpConvUintToInt8:
5704 case glslang::EOpConvUint64ToInt8:
5705 zero = builder.makeUint8Constant(0);
5706 break;
5707 case glslang::EOpConvInt8ToUint16:
5708 case glslang::EOpConvIntToUint16:
5709 case glslang::EOpConvInt64ToUint16:
5710 case glslang::EOpConvUint8ToInt16:
5711 case glslang::EOpConvUintToInt16:
5712 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005713 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005714 break;
5715 case glslang::EOpConvInt8ToUint:
5716 case glslang::EOpConvInt16ToUint:
5717 case glslang::EOpConvInt64ToUint:
5718 case glslang::EOpConvUint8ToInt:
5719 case glslang::EOpConvUint16ToInt:
5720 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005721 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005722 break;
5723 case glslang::EOpConvInt8ToUint64:
5724 case glslang::EOpConvInt16ToUint64:
5725 case glslang::EOpConvIntToUint64:
5726 case glslang::EOpConvUint8ToInt64:
5727 case glslang::EOpConvUint16ToInt64:
5728 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005729 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005730 break;
5731 default:
5732 assert(false && "Default missing");
5733 break;
5734 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005735 zero = makeSmearedConstant(zero, vectorSize);
5736 // Use OpIAdd, instead of OpBitcast to do the conversion when
5737 // generating for OpSpecConstantOp instruction.
5738 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5739 }
5740 // For normal run-time conversion instruction, use OpBitcast.
5741 convOp = spv::OpBitcast;
5742 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005743 default:
5744 break;
5745 }
5746
5747 spv::Id result = 0;
5748 if (convOp == spv::OpNop)
5749 return result;
5750
5751 if (convOp == spv::OpSelect) {
5752 zero = makeSmearedConstant(zero, vectorSize);
5753 one = makeSmearedConstant(one, vectorSize);
5754 result = builder.createTriOp(convOp, destType, operand, one, zero);
5755 } else
5756 result = builder.createUnaryOp(convOp, destType, operand);
5757
John Kessenichead86222018-03-28 18:01:20 -06005758 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005759 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005760 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005761}
5762
5763spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5764{
5765 if (vectorSize == 0)
5766 return constant;
5767
5768 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5769 std::vector<spv::Id> components;
5770 for (int c = 0; c < vectorSize; ++c)
5771 components.push_back(constant);
5772 return builder.makeCompositeConstant(vectorTypeId, components);
5773}
5774
John Kessenich426394d2015-07-23 10:22:48 -06005775// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005776spv::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 -06005777{
5778 spv::Op opCode = spv::OpNop;
5779
5780 switch (op) {
5781 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005782 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005783 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005784 opCode = spv::OpAtomicIAdd;
5785 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005786 case glslang::EOpAtomicCounterSubtract:
5787 opCode = spv::OpAtomicISub;
5788 break;
John Kessenich426394d2015-07-23 10:22:48 -06005789 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005790 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005791 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005792 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005793 break;
5794 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005795 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005796 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005797 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005798 break;
5799 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005800 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005801 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005802 opCode = spv::OpAtomicAnd;
5803 break;
5804 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005805 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005806 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005807 opCode = spv::OpAtomicOr;
5808 break;
5809 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005810 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005811 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005812 opCode = spv::OpAtomicXor;
5813 break;
5814 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005815 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005816 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005817 opCode = spv::OpAtomicExchange;
5818 break;
5819 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005820 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005821 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005822 opCode = spv::OpAtomicCompareExchange;
5823 break;
5824 case glslang::EOpAtomicCounterIncrement:
5825 opCode = spv::OpAtomicIIncrement;
5826 break;
5827 case glslang::EOpAtomicCounterDecrement:
5828 opCode = spv::OpAtomicIDecrement;
5829 break;
5830 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005831 case glslang::EOpImageAtomicLoad:
5832 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005833 opCode = spv::OpAtomicLoad;
5834 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005835 case glslang::EOpAtomicStore:
5836 case glslang::EOpImageAtomicStore:
5837 opCode = spv::OpAtomicStore;
5838 break;
John Kessenich426394d2015-07-23 10:22:48 -06005839 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005840 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005841 break;
5842 }
5843
Rex Xue8fe8b02017-09-26 15:42:56 +08005844 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5845 builder.addCapability(spv::CapabilityInt64Atomics);
5846
John Kessenich426394d2015-07-23 10:22:48 -06005847 // Sort out the operands
5848 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005849 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005850 // - compare-exchange swaps the value and comparator
5851 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005852 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005853 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5854 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5855 spv::Id scopeId;
5856 if (glslangIntermediate->usingVulkanMemoryModel()) {
5857 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5858 } else {
5859 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5860 }
5861 // semantics default to relaxed
5862 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5863 spv::Id semanticsId2 = semanticsId;
5864
5865 pointerId = operands[0];
5866 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5867 // no additional operands
5868 } else if (opCode == spv::OpAtomicCompareExchange) {
5869 compareId = operands[1];
5870 valueId = operands[2];
5871 if (operands.size() > 3) {
5872 scopeId = operands[3];
5873 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5874 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5875 }
5876 } else if (opCode == spv::OpAtomicLoad) {
5877 if (operands.size() > 1) {
5878 scopeId = operands[1];
5879 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5880 }
5881 } else {
5882 // atomic store or RMW
5883 valueId = operands[1];
5884 if (operands.size() > 2) {
5885 scopeId = operands[2];
5886 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5887 }
Rex Xu04db3f52015-09-16 11:44:02 +08005888 }
John Kessenich426394d2015-07-23 10:22:48 -06005889
Jeff Bolz36831c92018-09-05 10:11:41 -05005890 // Check for capabilities
5891 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5892 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5893 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5894 }
John Kessenich426394d2015-07-23 10:22:48 -06005895
Jeff Bolz36831c92018-09-05 10:11:41 -05005896 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5897 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5898 }
John Kessenich48d6e792017-10-06 21:21:48 -06005899
Jeff Bolz36831c92018-09-05 10:11:41 -05005900 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5901 spvAtomicOperands.push_back(pointerId);
5902 spvAtomicOperands.push_back(scopeId);
5903 spvAtomicOperands.push_back(semanticsId);
5904 if (opCode == spv::OpAtomicCompareExchange) {
5905 spvAtomicOperands.push_back(semanticsId2);
5906 spvAtomicOperands.push_back(valueId);
5907 spvAtomicOperands.push_back(compareId);
5908 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5909 spvAtomicOperands.push_back(valueId);
5910 }
John Kessenich48d6e792017-10-06 21:21:48 -06005911
Jeff Bolz36831c92018-09-05 10:11:41 -05005912 if (opCode == spv::OpAtomicStore) {
5913 builder.createNoResultOp(opCode, spvAtomicOperands);
5914 return 0;
5915 } else {
5916 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5917
5918 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5919 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5920 if (op == glslang::EOpAtomicCounterDecrement)
5921 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5922
5923 return resultId;
5924 }
John Kessenich426394d2015-07-23 10:22:48 -06005925}
5926
John Kessenich91cef522016-05-05 16:45:40 -06005927// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005928spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005929{
Corentin Walleze7061422018-08-08 15:20:15 +02005930#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005931 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5932 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005933#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005934
Rex Xu51596642016-09-21 18:56:12 +08005935 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005936 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005937 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5938
chaocf200da82016-12-20 12:44:35 -08005939 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5940 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005941 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5942 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005943 } else if (op == glslang::EOpAnyInvocation ||
5944 op == glslang::EOpAllInvocations ||
5945 op == glslang::EOpAllInvocationsEqual) {
5946 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5947 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005948 } else {
5949 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005950#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005951 if (op == glslang::EOpMinInvocationsNonUniform ||
5952 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005953 op == glslang::EOpAddInvocationsNonUniform ||
5954 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5955 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5956 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5957 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5958 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5959 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005960 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005961#endif
Rex Xu51596642016-09-21 18:56:12 +08005962
Rex Xu9d93a232016-05-05 12:30:44 +08005963#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005964 switch (op) {
5965 case glslang::EOpMinInvocations:
5966 case glslang::EOpMaxInvocations:
5967 case glslang::EOpAddInvocations:
5968 case glslang::EOpMinInvocationsNonUniform:
5969 case glslang::EOpMaxInvocationsNonUniform:
5970 case glslang::EOpAddInvocationsNonUniform:
5971 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005972 break;
5973 case glslang::EOpMinInvocationsInclusiveScan:
5974 case glslang::EOpMaxInvocationsInclusiveScan:
5975 case glslang::EOpAddInvocationsInclusiveScan:
5976 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5977 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5978 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5979 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005980 break;
5981 case glslang::EOpMinInvocationsExclusiveScan:
5982 case glslang::EOpMaxInvocationsExclusiveScan:
5983 case glslang::EOpAddInvocationsExclusiveScan:
5984 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5985 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5986 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5987 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005988 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005989 default:
5990 break;
Rex Xu430ef402016-10-14 17:22:23 +08005991 }
John Kessenich149afc32018-08-14 13:31:43 -06005992 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5993 spvGroupOperands.push_back(scope);
5994 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005995 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005996 spvGroupOperands.push_back(groupOp);
5997 }
Rex Xu9d93a232016-05-05 12:30:44 +08005998#endif
Rex Xu51596642016-09-21 18:56:12 +08005999 }
6000
John Kessenich149afc32018-08-14 13:31:43 -06006001 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6002 spv::IdImmediate op = { true, *opIt };
6003 spvGroupOperands.push_back(op);
6004 }
John Kessenich91cef522016-05-05 16:45:40 -06006005
6006 switch (op) {
6007 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006008 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006009 break;
John Kessenich91cef522016-05-05 16:45:40 -06006010 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006011 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006012 break;
John Kessenich91cef522016-05-05 16:45:40 -06006013 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006014 opCode = spv::OpSubgroupAllEqualKHR;
6015 break;
Rex Xu51596642016-09-21 18:56:12 +08006016 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006017 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006018 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006019 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006020 break;
6021 case glslang::EOpReadFirstInvocation:
6022 opCode = spv::OpSubgroupFirstInvocationKHR;
6023 break;
6024 case glslang::EOpBallot:
6025 {
6026 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6027 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6028 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6029 //
6030 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6031 //
6032 spv::Id uintType = builder.makeUintType(32);
6033 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6034 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6035
6036 std::vector<spv::Id> components;
6037 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6038 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6039
6040 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6041 return builder.createUnaryOp(spv::OpBitcast, typeId,
6042 builder.createCompositeConstruct(uvec2Type, components));
6043 }
6044
Rex Xu9d93a232016-05-05 12:30:44 +08006045#ifdef AMD_EXTENSIONS
6046 case glslang::EOpMinInvocations:
6047 case glslang::EOpMaxInvocations:
6048 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006049 case glslang::EOpMinInvocationsInclusiveScan:
6050 case glslang::EOpMaxInvocationsInclusiveScan:
6051 case glslang::EOpAddInvocationsInclusiveScan:
6052 case glslang::EOpMinInvocationsExclusiveScan:
6053 case glslang::EOpMaxInvocationsExclusiveScan:
6054 case glslang::EOpAddInvocationsExclusiveScan:
6055 if (op == glslang::EOpMinInvocations ||
6056 op == glslang::EOpMinInvocationsInclusiveScan ||
6057 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006058 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006059 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006060 else {
6061 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006062 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006063 else
Rex Xu51596642016-09-21 18:56:12 +08006064 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006065 }
Rex Xu430ef402016-10-14 17:22:23 +08006066 } else if (op == glslang::EOpMaxInvocations ||
6067 op == glslang::EOpMaxInvocationsInclusiveScan ||
6068 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006069 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006070 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006071 else {
6072 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006073 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006074 else
Rex Xu51596642016-09-21 18:56:12 +08006075 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006076 }
6077 } else {
6078 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006079 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006080 else
Rex Xu51596642016-09-21 18:56:12 +08006081 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006082 }
6083
Rex Xu2bbbe062016-08-23 15:41:05 +08006084 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006085 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006086
6087 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006088 case glslang::EOpMinInvocationsNonUniform:
6089 case glslang::EOpMaxInvocationsNonUniform:
6090 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006091 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6092 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6093 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6094 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6095 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6096 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6097 if (op == glslang::EOpMinInvocationsNonUniform ||
6098 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6099 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006100 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006101 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006102 else {
6103 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006104 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006105 else
Rex Xu51596642016-09-21 18:56:12 +08006106 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006107 }
6108 }
Rex Xu430ef402016-10-14 17:22:23 +08006109 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6110 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6111 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006112 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006113 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006114 else {
6115 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006116 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006117 else
Rex Xu51596642016-09-21 18:56:12 +08006118 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006119 }
6120 }
6121 else {
6122 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006123 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006124 else
Rex Xu51596642016-09-21 18:56:12 +08006125 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006126 }
6127
Rex Xu2bbbe062016-08-23 15:41:05 +08006128 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006129 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006130
6131 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006132#endif
John Kessenich91cef522016-05-05 16:45:40 -06006133 default:
6134 logger->missingFunctionality("invocation operation");
6135 return spv::NoResult;
6136 }
Rex Xu51596642016-09-21 18:56:12 +08006137
6138 assert(opCode != spv::OpNop);
6139 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006140}
6141
Rex Xu2bbbe062016-08-23 15:41:05 +08006142// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006143spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6144 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006145{
Rex Xub7072052016-09-26 15:53:40 +08006146#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006147 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6148 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006149 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006150 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006151 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6152 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6153 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006154#else
6155 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6156 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006157 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6158 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006159#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006160
6161 // Handle group invocation operations scalar by scalar.
6162 // The result type is the same type as the original type.
6163 // The algorithm is to:
6164 // - break the vector into scalars
6165 // - apply the operation to each scalar
6166 // - make a vector out the scalar results
6167
6168 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006169 int numComponents = builder.getNumComponents(operands[0]);
6170 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006171 std::vector<spv::Id> results;
6172
6173 // do each scalar op
6174 for (int comp = 0; comp < numComponents; ++comp) {
6175 std::vector<unsigned int> indexes;
6176 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006177 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6178 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006179 if (op == spv::OpSubgroupReadInvocationKHR) {
6180 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006181 spv::IdImmediate operand = { true, operands[1] };
6182 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006183 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006184 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6185 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006186 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006187 spv::IdImmediate operand = { true, operands[1] };
6188 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006189 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006190 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6191 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006192 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006193 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006194 spvGroupOperands.push_back(scalar);
6195 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006196
Rex Xub7072052016-09-26 15:53:40 +08006197 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006198 }
6199
6200 // put the pieces together
6201 return builder.createCompositeConstruct(typeId, results);
6202}
Rex Xu2bbbe062016-08-23 15:41:05 +08006203
John Kessenich66011cb2018-03-06 16:12:04 -07006204// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006205spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6206 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006207{
6208 // Add the required capabilities.
6209 switch (op) {
6210 case glslang::EOpSubgroupElect:
6211 builder.addCapability(spv::CapabilityGroupNonUniform);
6212 break;
6213 case glslang::EOpSubgroupAll:
6214 case glslang::EOpSubgroupAny:
6215 case glslang::EOpSubgroupAllEqual:
6216 builder.addCapability(spv::CapabilityGroupNonUniform);
6217 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6218 break;
6219 case glslang::EOpSubgroupBroadcast:
6220 case glslang::EOpSubgroupBroadcastFirst:
6221 case glslang::EOpSubgroupBallot:
6222 case glslang::EOpSubgroupInverseBallot:
6223 case glslang::EOpSubgroupBallotBitExtract:
6224 case glslang::EOpSubgroupBallotBitCount:
6225 case glslang::EOpSubgroupBallotInclusiveBitCount:
6226 case glslang::EOpSubgroupBallotExclusiveBitCount:
6227 case glslang::EOpSubgroupBallotFindLSB:
6228 case glslang::EOpSubgroupBallotFindMSB:
6229 builder.addCapability(spv::CapabilityGroupNonUniform);
6230 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6231 break;
6232 case glslang::EOpSubgroupShuffle:
6233 case glslang::EOpSubgroupShuffleXor:
6234 builder.addCapability(spv::CapabilityGroupNonUniform);
6235 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6236 break;
6237 case glslang::EOpSubgroupShuffleUp:
6238 case glslang::EOpSubgroupShuffleDown:
6239 builder.addCapability(spv::CapabilityGroupNonUniform);
6240 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6241 break;
6242 case glslang::EOpSubgroupAdd:
6243 case glslang::EOpSubgroupMul:
6244 case glslang::EOpSubgroupMin:
6245 case glslang::EOpSubgroupMax:
6246 case glslang::EOpSubgroupAnd:
6247 case glslang::EOpSubgroupOr:
6248 case glslang::EOpSubgroupXor:
6249 case glslang::EOpSubgroupInclusiveAdd:
6250 case glslang::EOpSubgroupInclusiveMul:
6251 case glslang::EOpSubgroupInclusiveMin:
6252 case glslang::EOpSubgroupInclusiveMax:
6253 case glslang::EOpSubgroupInclusiveAnd:
6254 case glslang::EOpSubgroupInclusiveOr:
6255 case glslang::EOpSubgroupInclusiveXor:
6256 case glslang::EOpSubgroupExclusiveAdd:
6257 case glslang::EOpSubgroupExclusiveMul:
6258 case glslang::EOpSubgroupExclusiveMin:
6259 case glslang::EOpSubgroupExclusiveMax:
6260 case glslang::EOpSubgroupExclusiveAnd:
6261 case glslang::EOpSubgroupExclusiveOr:
6262 case glslang::EOpSubgroupExclusiveXor:
6263 builder.addCapability(spv::CapabilityGroupNonUniform);
6264 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6265 break;
6266 case glslang::EOpSubgroupClusteredAdd:
6267 case glslang::EOpSubgroupClusteredMul:
6268 case glslang::EOpSubgroupClusteredMin:
6269 case glslang::EOpSubgroupClusteredMax:
6270 case glslang::EOpSubgroupClusteredAnd:
6271 case glslang::EOpSubgroupClusteredOr:
6272 case glslang::EOpSubgroupClusteredXor:
6273 builder.addCapability(spv::CapabilityGroupNonUniform);
6274 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6275 break;
6276 case glslang::EOpSubgroupQuadBroadcast:
6277 case glslang::EOpSubgroupQuadSwapHorizontal:
6278 case glslang::EOpSubgroupQuadSwapVertical:
6279 case glslang::EOpSubgroupQuadSwapDiagonal:
6280 builder.addCapability(spv::CapabilityGroupNonUniform);
6281 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6282 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006283#ifdef NV_EXTENSIONS
6284 case glslang::EOpSubgroupPartitionedAdd:
6285 case glslang::EOpSubgroupPartitionedMul:
6286 case glslang::EOpSubgroupPartitionedMin:
6287 case glslang::EOpSubgroupPartitionedMax:
6288 case glslang::EOpSubgroupPartitionedAnd:
6289 case glslang::EOpSubgroupPartitionedOr:
6290 case glslang::EOpSubgroupPartitionedXor:
6291 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6292 case glslang::EOpSubgroupPartitionedInclusiveMul:
6293 case glslang::EOpSubgroupPartitionedInclusiveMin:
6294 case glslang::EOpSubgroupPartitionedInclusiveMax:
6295 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6296 case glslang::EOpSubgroupPartitionedInclusiveOr:
6297 case glslang::EOpSubgroupPartitionedInclusiveXor:
6298 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6299 case glslang::EOpSubgroupPartitionedExclusiveMul:
6300 case glslang::EOpSubgroupPartitionedExclusiveMin:
6301 case glslang::EOpSubgroupPartitionedExclusiveMax:
6302 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6303 case glslang::EOpSubgroupPartitionedExclusiveOr:
6304 case glslang::EOpSubgroupPartitionedExclusiveXor:
6305 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6306 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6307 break;
6308#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006309 default: assert(0 && "Unhandled subgroup operation!");
6310 }
6311
6312 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6313 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6314 const bool isBool = typeProxy == glslang::EbtBool;
6315
6316 spv::Op opCode = spv::OpNop;
6317
6318 // Figure out which opcode to use.
6319 switch (op) {
6320 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6321 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6322 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6323 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6324 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6325 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6326 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6327 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6328 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6329 case glslang::EOpSubgroupBallotBitCount:
6330 case glslang::EOpSubgroupBallotInclusiveBitCount:
6331 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6332 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6333 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6334 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6335 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6336 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6337 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6338 case glslang::EOpSubgroupAdd:
6339 case glslang::EOpSubgroupInclusiveAdd:
6340 case glslang::EOpSubgroupExclusiveAdd:
6341 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006342#ifdef NV_EXTENSIONS
6343 case glslang::EOpSubgroupPartitionedAdd:
6344 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6345 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6346#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006347 if (isFloat) {
6348 opCode = spv::OpGroupNonUniformFAdd;
6349 } else {
6350 opCode = spv::OpGroupNonUniformIAdd;
6351 }
6352 break;
6353 case glslang::EOpSubgroupMul:
6354 case glslang::EOpSubgroupInclusiveMul:
6355 case glslang::EOpSubgroupExclusiveMul:
6356 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006357#ifdef NV_EXTENSIONS
6358 case glslang::EOpSubgroupPartitionedMul:
6359 case glslang::EOpSubgroupPartitionedInclusiveMul:
6360 case glslang::EOpSubgroupPartitionedExclusiveMul:
6361#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006362 if (isFloat) {
6363 opCode = spv::OpGroupNonUniformFMul;
6364 } else {
6365 opCode = spv::OpGroupNonUniformIMul;
6366 }
6367 break;
6368 case glslang::EOpSubgroupMin:
6369 case glslang::EOpSubgroupInclusiveMin:
6370 case glslang::EOpSubgroupExclusiveMin:
6371 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006372#ifdef NV_EXTENSIONS
6373 case glslang::EOpSubgroupPartitionedMin:
6374 case glslang::EOpSubgroupPartitionedInclusiveMin:
6375 case glslang::EOpSubgroupPartitionedExclusiveMin:
6376#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006377 if (isFloat) {
6378 opCode = spv::OpGroupNonUniformFMin;
6379 } else if (isUnsigned) {
6380 opCode = spv::OpGroupNonUniformUMin;
6381 } else {
6382 opCode = spv::OpGroupNonUniformSMin;
6383 }
6384 break;
6385 case glslang::EOpSubgroupMax:
6386 case glslang::EOpSubgroupInclusiveMax:
6387 case glslang::EOpSubgroupExclusiveMax:
6388 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006389#ifdef NV_EXTENSIONS
6390 case glslang::EOpSubgroupPartitionedMax:
6391 case glslang::EOpSubgroupPartitionedInclusiveMax:
6392 case glslang::EOpSubgroupPartitionedExclusiveMax:
6393#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006394 if (isFloat) {
6395 opCode = spv::OpGroupNonUniformFMax;
6396 } else if (isUnsigned) {
6397 opCode = spv::OpGroupNonUniformUMax;
6398 } else {
6399 opCode = spv::OpGroupNonUniformSMax;
6400 }
6401 break;
6402 case glslang::EOpSubgroupAnd:
6403 case glslang::EOpSubgroupInclusiveAnd:
6404 case glslang::EOpSubgroupExclusiveAnd:
6405 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006406#ifdef NV_EXTENSIONS
6407 case glslang::EOpSubgroupPartitionedAnd:
6408 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6409 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6410#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006411 if (isBool) {
6412 opCode = spv::OpGroupNonUniformLogicalAnd;
6413 } else {
6414 opCode = spv::OpGroupNonUniformBitwiseAnd;
6415 }
6416 break;
6417 case glslang::EOpSubgroupOr:
6418 case glslang::EOpSubgroupInclusiveOr:
6419 case glslang::EOpSubgroupExclusiveOr:
6420 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006421#ifdef NV_EXTENSIONS
6422 case glslang::EOpSubgroupPartitionedOr:
6423 case glslang::EOpSubgroupPartitionedInclusiveOr:
6424 case glslang::EOpSubgroupPartitionedExclusiveOr:
6425#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006426 if (isBool) {
6427 opCode = spv::OpGroupNonUniformLogicalOr;
6428 } else {
6429 opCode = spv::OpGroupNonUniformBitwiseOr;
6430 }
6431 break;
6432 case glslang::EOpSubgroupXor:
6433 case glslang::EOpSubgroupInclusiveXor:
6434 case glslang::EOpSubgroupExclusiveXor:
6435 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006436#ifdef NV_EXTENSIONS
6437 case glslang::EOpSubgroupPartitionedXor:
6438 case glslang::EOpSubgroupPartitionedInclusiveXor:
6439 case glslang::EOpSubgroupPartitionedExclusiveXor:
6440#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006441 if (isBool) {
6442 opCode = spv::OpGroupNonUniformLogicalXor;
6443 } else {
6444 opCode = spv::OpGroupNonUniformBitwiseXor;
6445 }
6446 break;
6447 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6448 case glslang::EOpSubgroupQuadSwapHorizontal:
6449 case glslang::EOpSubgroupQuadSwapVertical:
6450 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6451 default: assert(0 && "Unhandled subgroup operation!");
6452 }
6453
John Kessenich149afc32018-08-14 13:31:43 -06006454 // get the right Group Operation
6455 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006456 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006457 default:
6458 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006459 case glslang::EOpSubgroupBallotBitCount:
6460 case glslang::EOpSubgroupAdd:
6461 case glslang::EOpSubgroupMul:
6462 case glslang::EOpSubgroupMin:
6463 case glslang::EOpSubgroupMax:
6464 case glslang::EOpSubgroupAnd:
6465 case glslang::EOpSubgroupOr:
6466 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006467 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006468 break;
6469 case glslang::EOpSubgroupBallotInclusiveBitCount:
6470 case glslang::EOpSubgroupInclusiveAdd:
6471 case glslang::EOpSubgroupInclusiveMul:
6472 case glslang::EOpSubgroupInclusiveMin:
6473 case glslang::EOpSubgroupInclusiveMax:
6474 case glslang::EOpSubgroupInclusiveAnd:
6475 case glslang::EOpSubgroupInclusiveOr:
6476 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006477 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006478 break;
6479 case glslang::EOpSubgroupBallotExclusiveBitCount:
6480 case glslang::EOpSubgroupExclusiveAdd:
6481 case glslang::EOpSubgroupExclusiveMul:
6482 case glslang::EOpSubgroupExclusiveMin:
6483 case glslang::EOpSubgroupExclusiveMax:
6484 case glslang::EOpSubgroupExclusiveAnd:
6485 case glslang::EOpSubgroupExclusiveOr:
6486 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006487 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006488 break;
6489 case glslang::EOpSubgroupClusteredAdd:
6490 case glslang::EOpSubgroupClusteredMul:
6491 case glslang::EOpSubgroupClusteredMin:
6492 case glslang::EOpSubgroupClusteredMax:
6493 case glslang::EOpSubgroupClusteredAnd:
6494 case glslang::EOpSubgroupClusteredOr:
6495 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006496 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006497 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006498#ifdef NV_EXTENSIONS
6499 case glslang::EOpSubgroupPartitionedAdd:
6500 case glslang::EOpSubgroupPartitionedMul:
6501 case glslang::EOpSubgroupPartitionedMin:
6502 case glslang::EOpSubgroupPartitionedMax:
6503 case glslang::EOpSubgroupPartitionedAnd:
6504 case glslang::EOpSubgroupPartitionedOr:
6505 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006506 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006507 break;
6508 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6509 case glslang::EOpSubgroupPartitionedInclusiveMul:
6510 case glslang::EOpSubgroupPartitionedInclusiveMin:
6511 case glslang::EOpSubgroupPartitionedInclusiveMax:
6512 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6513 case glslang::EOpSubgroupPartitionedInclusiveOr:
6514 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006515 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006516 break;
6517 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6518 case glslang::EOpSubgroupPartitionedExclusiveMul:
6519 case glslang::EOpSubgroupPartitionedExclusiveMin:
6520 case glslang::EOpSubgroupPartitionedExclusiveMax:
6521 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6522 case glslang::EOpSubgroupPartitionedExclusiveOr:
6523 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006524 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006525 break;
6526#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006527 }
6528
John Kessenich149afc32018-08-14 13:31:43 -06006529 // build the instruction
6530 std::vector<spv::IdImmediate> spvGroupOperands;
6531
6532 // Every operation begins with the Execution Scope operand.
6533 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6534 spvGroupOperands.push_back(executionScope);
6535
6536 // Next, for all operations that use a Group Operation, push that as an operand.
6537 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006538 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006539 spvGroupOperands.push_back(groupOperand);
6540 }
6541
John Kessenich66011cb2018-03-06 16:12:04 -07006542 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006543 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6544 spv::IdImmediate operand = { true, *opIt };
6545 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006546 }
6547
6548 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006549 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006550 switch (op) {
6551 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006552 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6553 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6554 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6555 }
6556 if (directionId != spv::NoResult) {
6557 spv::IdImmediate direction = { true, directionId };
6558 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006559 }
6560
6561 return builder.createOp(opCode, typeId, spvGroupOperands);
6562}
6563
John Kessenich5e4b1242015-08-06 22:53:06 -06006564spv::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 -06006565{
John Kessenich66011cb2018-03-06 16:12:04 -07006566 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6567 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006568
John Kessenich140f3df2015-06-26 16:58:36 -06006569 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006570 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006571 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006572 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006573 spv::Id typeId0 = 0;
6574 if (consumedOperands > 0)
6575 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006576 spv::Id typeId1 = 0;
6577 if (consumedOperands > 1)
6578 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006579 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006580
6581 switch (op) {
6582 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006583 if (isFloat)
6584 libCall = spv::GLSLstd450FMin;
6585 else if (isUnsigned)
6586 libCall = spv::GLSLstd450UMin;
6587 else
6588 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006589 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006590 break;
6591 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006592 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006593 break;
6594 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006595 if (isFloat)
6596 libCall = spv::GLSLstd450FMax;
6597 else if (isUnsigned)
6598 libCall = spv::GLSLstd450UMax;
6599 else
6600 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006601 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006602 break;
6603 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006604 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006605 break;
6606 case glslang::EOpDot:
6607 opCode = spv::OpDot;
6608 break;
6609 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006610 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006611 break;
6612
6613 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006614 if (isFloat)
6615 libCall = spv::GLSLstd450FClamp;
6616 else if (isUnsigned)
6617 libCall = spv::GLSLstd450UClamp;
6618 else
6619 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006620 builder.promoteScalar(precision, operands.front(), operands[1]);
6621 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006622 break;
6623 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006624 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6625 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006626 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006627 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006628 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006629 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006630 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006631 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006632 break;
6633 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006634 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006635 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006636 break;
6637 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006638 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006639 builder.promoteScalar(precision, operands[0], operands[2]);
6640 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006641 break;
6642
6643 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006644 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006645 break;
6646 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006647 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006648 break;
6649 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006650 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006651 break;
6652 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006653 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006654 break;
6655 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006656 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006657 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006658 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006659#ifdef AMD_EXTENSIONS
6660 if (typeProxy == glslang::EbtFloat16)
6661 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6662#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006663 libCall = spv::GLSLstd450InterpolateAtSample;
6664 break;
6665 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006666#ifdef AMD_EXTENSIONS
6667 if (typeProxy == glslang::EbtFloat16)
6668 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6669#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006670 libCall = spv::GLSLstd450InterpolateAtOffset;
6671 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006672 case glslang::EOpAddCarry:
6673 opCode = spv::OpIAddCarry;
6674 typeId = builder.makeStructResultType(typeId0, typeId0);
6675 consumedOperands = 2;
6676 break;
6677 case glslang::EOpSubBorrow:
6678 opCode = spv::OpISubBorrow;
6679 typeId = builder.makeStructResultType(typeId0, typeId0);
6680 consumedOperands = 2;
6681 break;
6682 case glslang::EOpUMulExtended:
6683 opCode = spv::OpUMulExtended;
6684 typeId = builder.makeStructResultType(typeId0, typeId0);
6685 consumedOperands = 2;
6686 break;
6687 case glslang::EOpIMulExtended:
6688 opCode = spv::OpSMulExtended;
6689 typeId = builder.makeStructResultType(typeId0, typeId0);
6690 consumedOperands = 2;
6691 break;
6692 case glslang::EOpBitfieldExtract:
6693 if (isUnsigned)
6694 opCode = spv::OpBitFieldUExtract;
6695 else
6696 opCode = spv::OpBitFieldSExtract;
6697 break;
6698 case glslang::EOpBitfieldInsert:
6699 opCode = spv::OpBitFieldInsert;
6700 break;
6701
6702 case glslang::EOpFma:
6703 libCall = spv::GLSLstd450Fma;
6704 break;
6705 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006706 {
6707 libCall = spv::GLSLstd450FrexpStruct;
6708 assert(builder.isPointerType(typeId1));
6709 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006710 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006711#ifdef AMD_EXTENSIONS
6712 if (width == 16)
6713 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6714 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6715#endif
Rex Xu470026f2017-03-29 17:12:40 +08006716 if (builder.getNumComponents(operands[0]) == 1)
6717 frexpIntType = builder.makeIntegerType(width, true);
6718 else
6719 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6720 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6721 consumedOperands = 1;
6722 }
John Kessenich55e7d112015-11-15 21:33:39 -07006723 break;
6724 case glslang::EOpLdexp:
6725 libCall = spv::GLSLstd450Ldexp;
6726 break;
6727
Rex Xu574ab042016-04-14 16:53:07 +08006728 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006729 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006730
John Kessenich66011cb2018-03-06 16:12:04 -07006731 case glslang::EOpSubgroupBroadcast:
6732 case glslang::EOpSubgroupBallotBitExtract:
6733 case glslang::EOpSubgroupShuffle:
6734 case glslang::EOpSubgroupShuffleXor:
6735 case glslang::EOpSubgroupShuffleUp:
6736 case glslang::EOpSubgroupShuffleDown:
6737 case glslang::EOpSubgroupClusteredAdd:
6738 case glslang::EOpSubgroupClusteredMul:
6739 case glslang::EOpSubgroupClusteredMin:
6740 case glslang::EOpSubgroupClusteredMax:
6741 case glslang::EOpSubgroupClusteredAnd:
6742 case glslang::EOpSubgroupClusteredOr:
6743 case glslang::EOpSubgroupClusteredXor:
6744 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006745#ifdef NV_EXTENSIONS
6746 case glslang::EOpSubgroupPartitionedAdd:
6747 case glslang::EOpSubgroupPartitionedMul:
6748 case glslang::EOpSubgroupPartitionedMin:
6749 case glslang::EOpSubgroupPartitionedMax:
6750 case glslang::EOpSubgroupPartitionedAnd:
6751 case glslang::EOpSubgroupPartitionedOr:
6752 case glslang::EOpSubgroupPartitionedXor:
6753 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6754 case glslang::EOpSubgroupPartitionedInclusiveMul:
6755 case glslang::EOpSubgroupPartitionedInclusiveMin:
6756 case glslang::EOpSubgroupPartitionedInclusiveMax:
6757 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6758 case glslang::EOpSubgroupPartitionedInclusiveOr:
6759 case glslang::EOpSubgroupPartitionedInclusiveXor:
6760 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6761 case glslang::EOpSubgroupPartitionedExclusiveMul:
6762 case glslang::EOpSubgroupPartitionedExclusiveMin:
6763 case glslang::EOpSubgroupPartitionedExclusiveMax:
6764 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6765 case glslang::EOpSubgroupPartitionedExclusiveOr:
6766 case glslang::EOpSubgroupPartitionedExclusiveXor:
6767#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006768 return createSubgroupOperation(op, typeId, operands, typeProxy);
6769
Rex Xu9d93a232016-05-05 12:30:44 +08006770#ifdef AMD_EXTENSIONS
6771 case glslang::EOpSwizzleInvocations:
6772 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6773 libCall = spv::SwizzleInvocationsAMD;
6774 break;
6775 case glslang::EOpSwizzleInvocationsMasked:
6776 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6777 libCall = spv::SwizzleInvocationsMaskedAMD;
6778 break;
6779 case glslang::EOpWriteInvocation:
6780 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6781 libCall = spv::WriteInvocationAMD;
6782 break;
6783
6784 case glslang::EOpMin3:
6785 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6786 if (isFloat)
6787 libCall = spv::FMin3AMD;
6788 else {
6789 if (isUnsigned)
6790 libCall = spv::UMin3AMD;
6791 else
6792 libCall = spv::SMin3AMD;
6793 }
6794 break;
6795 case glslang::EOpMax3:
6796 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6797 if (isFloat)
6798 libCall = spv::FMax3AMD;
6799 else {
6800 if (isUnsigned)
6801 libCall = spv::UMax3AMD;
6802 else
6803 libCall = spv::SMax3AMD;
6804 }
6805 break;
6806 case glslang::EOpMid3:
6807 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6808 if (isFloat)
6809 libCall = spv::FMid3AMD;
6810 else {
6811 if (isUnsigned)
6812 libCall = spv::UMid3AMD;
6813 else
6814 libCall = spv::SMid3AMD;
6815 }
6816 break;
6817
6818 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006819 if (typeProxy == glslang::EbtFloat16)
6820 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006821 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6822 libCall = spv::InterpolateAtVertexAMD;
6823 break;
6824#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006825 case glslang::EOpBarrier:
6826 {
6827 // This is for the extended controlBarrier function, with four operands.
6828 // The unextended barrier() goes through createNoArgOperation.
6829 assert(operands.size() == 4);
6830 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6831 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6832 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6833 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6834 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6835 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6836 }
6837 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6838 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6839 }
6840 return 0;
6841 }
6842 break;
6843 case glslang::EOpMemoryBarrier:
6844 {
6845 // This is for the extended memoryBarrier function, with three operands.
6846 // The unextended memoryBarrier() goes through createNoArgOperation.
6847 assert(operands.size() == 3);
6848 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6849 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6850 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6851 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6852 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6853 }
6854 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6855 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6856 }
6857 return 0;
6858 }
6859 break;
Chao Chen3c366992018-09-19 11:41:59 -07006860
6861#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006862 case glslang::EOpReportIntersectionNV:
6863 {
6864 typeId = builder.makeBoolType();
6865 opCode = spv::OpReportIntersectionNVX;
6866 }
6867 break;
6868 case glslang::EOpTraceNV:
6869 {
6870 builder.createNoResultOp(spv::OpTraceNVX, operands);
6871 return 0;
6872 }
6873 break;
Chao Chen3c366992018-09-19 11:41:59 -07006874 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6875 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6876 return 0;
6877#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006878 default:
6879 return 0;
6880 }
6881
6882 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006883 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006884 // Use an extended instruction from the standard library.
6885 // Construct the call arguments, without modifying the original operands vector.
6886 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6887 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006888 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006889 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006890 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006891 case 0:
6892 // should all be handled by visitAggregate and createNoArgOperation
6893 assert(0);
6894 return 0;
6895 case 1:
6896 // should all be handled by createUnaryOperation
6897 assert(0);
6898 return 0;
6899 case 2:
6900 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6901 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006902 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006903 // anything 3 or over doesn't have l-value operands, so all should be consumed
6904 assert(consumedOperands == operands.size());
6905 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006906 break;
6907 }
6908 }
6909
John Kessenich55e7d112015-11-15 21:33:39 -07006910 // Decode the return types that were structures
6911 switch (op) {
6912 case glslang::EOpAddCarry:
6913 case glslang::EOpSubBorrow:
6914 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6915 id = builder.createCompositeExtract(id, typeId0, 0);
6916 break;
6917 case glslang::EOpUMulExtended:
6918 case glslang::EOpIMulExtended:
6919 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6920 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6921 break;
6922 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006923 {
6924 assert(operands.size() == 2);
6925 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6926 // "exp" is floating-point type (from HLSL intrinsic)
6927 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6928 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6929 builder.createStore(member1, operands[1]);
6930 } else
6931 // "exp" is integer type (from GLSL built-in function)
6932 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6933 id = builder.createCompositeExtract(id, typeId0, 0);
6934 }
John Kessenich55e7d112015-11-15 21:33:39 -07006935 break;
6936 default:
6937 break;
6938 }
6939
John Kessenich32cfd492016-02-02 12:37:46 -07006940 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006941}
6942
Rex Xu9d93a232016-05-05 12:30:44 +08006943// Intrinsics with no arguments (or no return value, and no precision).
6944spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006945{
Jeff Bolz36831c92018-09-05 10:11:41 -05006946 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6947 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006948
6949 switch (op) {
6950 case glslang::EOpEmitVertex:
6951 builder.createNoResultOp(spv::OpEmitVertex);
6952 return 0;
6953 case glslang::EOpEndPrimitive:
6954 builder.createNoResultOp(spv::OpEndPrimitive);
6955 return 0;
6956 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006957 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006958 if (glslangIntermediate->usingVulkanMemoryModel()) {
6959 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6960 spv::MemorySemanticsOutputMemoryKHRMask |
6961 spv::MemorySemanticsAcquireReleaseMask);
6962 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6963 } else {
6964 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6965 }
John Kessenich82979362017-12-11 04:02:24 -07006966 } else {
6967 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6968 spv::MemorySemanticsWorkgroupMemoryMask |
6969 spv::MemorySemanticsAcquireReleaseMask);
6970 }
John Kessenich140f3df2015-06-26 16:58:36 -06006971 return 0;
6972 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006973 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6974 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006975 return 0;
6976 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006977 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6978 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006979 return 0;
6980 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006981 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6982 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006983 return 0;
6984 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006985 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6986 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006987 return 0;
6988 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006989 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6990 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006991 return 0;
6992 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006993 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6994 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006995 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006996 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006997 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006998 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006999 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007000 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007001 case glslang::EOpDeviceMemoryBarrier:
7002 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7003 spv::MemorySemanticsImageMemoryMask |
7004 spv::MemorySemanticsAcquireReleaseMask);
7005 return 0;
7006 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7007 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7008 spv::MemorySemanticsImageMemoryMask |
7009 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007010 return 0;
7011 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007012 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7013 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007014 return 0;
7015 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007016 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7017 spv::MemorySemanticsWorkgroupMemoryMask |
7018 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007019 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007020 case glslang::EOpSubgroupBarrier:
7021 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7022 spv::MemorySemanticsAcquireReleaseMask);
7023 return spv::NoResult;
7024 case glslang::EOpSubgroupMemoryBarrier:
7025 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7026 spv::MemorySemanticsAcquireReleaseMask);
7027 return spv::NoResult;
7028 case glslang::EOpSubgroupMemoryBarrierBuffer:
7029 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7030 spv::MemorySemanticsAcquireReleaseMask);
7031 return spv::NoResult;
7032 case glslang::EOpSubgroupMemoryBarrierImage:
7033 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7034 spv::MemorySemanticsAcquireReleaseMask);
7035 return spv::NoResult;
7036 case glslang::EOpSubgroupMemoryBarrierShared:
7037 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7038 spv::MemorySemanticsAcquireReleaseMask);
7039 return spv::NoResult;
7040 case glslang::EOpSubgroupElect: {
7041 std::vector<spv::Id> operands;
7042 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7043 }
Rex Xu9d93a232016-05-05 12:30:44 +08007044#ifdef AMD_EXTENSIONS
7045 case glslang::EOpTime:
7046 {
7047 std::vector<spv::Id> args; // Dummy arguments
7048 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7049 return builder.setPrecision(id, precision);
7050 }
7051#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007052#ifdef NV_EXTENSIONS
7053 case glslang::EOpIgnoreIntersectionNV:
7054 builder.createNoResultOp(spv::OpIgnoreIntersectionNVX);
7055 return 0;
7056 case glslang::EOpTerminateRayNV:
7057 builder.createNoResultOp(spv::OpTerminateRayNVX);
7058 return 0;
7059#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007060 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007061 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007062 return 0;
7063 }
7064}
7065
7066spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7067{
John Kessenich2f273362015-07-18 22:34:27 -06007068 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007069 spv::Id id;
7070 if (symbolValues.end() != iter) {
7071 id = iter->second;
7072 return id;
7073 }
7074
7075 // it was not found, create it
7076 id = createSpvVariable(symbol);
7077 symbolValues[symbol->getId()] = id;
7078
Rex Xuc884b4a2016-06-29 15:03:44 +08007079 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007080 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7081 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7082 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007083#ifdef NV_EXTENSIONS
7084 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7085#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007086 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007087 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007088 if (symbol->getQualifier().hasIndex())
7089 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7090 if (symbol->getQualifier().hasComponent())
7091 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007092 // atomic counters use this:
7093 if (symbol->getQualifier().hasOffset())
7094 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007095 }
7096
scygan2c864272016-05-18 18:09:17 +02007097 if (symbol->getQualifier().hasLocation())
7098 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007099 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007100 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007101 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007102 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007103 }
John Kessenich140f3df2015-06-26 16:58:36 -06007104 if (symbol->getQualifier().hasSet())
7105 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007106 else if (IsDescriptorResource(symbol->getType())) {
7107 // default to 0
7108 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7109 }
John Kessenich140f3df2015-06-26 16:58:36 -06007110 if (symbol->getQualifier().hasBinding())
7111 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007112 if (symbol->getQualifier().hasAttachment())
7113 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007114 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007115 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007116 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007117 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007118 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007119 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007120 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7121 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7122 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7123 }
7124 if (symbol->getQualifier().hasXfbOffset())
7125 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007126 }
7127
Rex Xu1da878f2016-02-21 20:59:01 +08007128 if (symbol->getType().isImage()) {
7129 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007130 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007131 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007132 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007133 }
7134
John Kessenich140f3df2015-06-26 16:58:36 -06007135 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007136 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007137 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007138 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007139
John Kessenich5611c6d2018-04-05 11:25:02 -06007140 // nonuniform
7141 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7142
John Kessenichecba76f2017-01-06 00:34:48 -07007143#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007144 if (builtIn == spv::BuiltInSampleMask) {
7145 spv::Decoration decoration;
7146 // GL_NV_sample_mask_override_coverage extension
7147 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007148 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007149 else
7150 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007151 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007152 if (decoration != spv::DecorationMax) {
7153 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7154 }
7155 }
chaoc771d89f2017-01-13 01:10:53 -08007156 else if (builtIn == spv::BuiltInLayer) {
7157 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007158 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007159 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007160 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7161 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7162 }
John Kessenichb41bff62017-08-11 13:07:17 -06007163 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007164 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7165 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007166 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7167 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7168 }
7169 }
7170
chaoc6e5acae2016-12-20 13:28:52 -08007171 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007172 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007173 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007174 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7175 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007176 if (symbol->getQualifier().pervertexNV) {
7177 builder.addDecoration(id, spv::DecorationPerVertexNV);
7178 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7179 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7180 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007181#endif
7182
John Kessenich5d610ee2018-03-07 18:05:55 -07007183 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7184 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7185 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7186 symbol->getType().getQualifier().semanticName);
7187 }
7188
John Kessenich140f3df2015-06-26 16:58:36 -06007189 return id;
7190}
7191
Chao Chen3c366992018-09-19 11:41:59 -07007192#ifdef NV_EXTENSIONS
7193// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7194void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7195{
7196 if (member >= 0) {
7197 if (qualifier.perPrimitiveNV)
7198 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
7199 if (qualifier.perViewNV)
7200 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7201 if (qualifier.perTaskNV)
7202 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7203 } else {
7204 if (qualifier.perPrimitiveNV)
7205 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
7206 if (qualifier.perViewNV)
7207 builder.addDecoration(id, spv::DecorationPerViewNV);
7208 if (qualifier.perTaskNV)
7209 builder.addDecoration(id, spv::DecorationPerTaskNV);
7210 }
7211}
7212#endif
7213
John Kessenich55e7d112015-11-15 21:33:39 -07007214// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007215// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007216//
7217// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7218//
7219// Recursively walk the nodes. The nodes form a tree whose leaves are
7220// regular constants, which themselves are trees that createSpvConstant()
7221// recursively walks. So, this function walks the "top" of the tree:
7222// - emit specialization constant-building instructions for specConstant
7223// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007224spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007225{
John Kessenich7cc0e282016-03-20 00:46:02 -06007226 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007227
qining4f4bb812016-04-03 23:55:17 -04007228 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007229 if (! node.getQualifier().specConstant) {
7230 // hand off to the non-spec-constant path
7231 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7232 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007233 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007234 nextConst, false);
7235 }
7236
7237 // We now know we have a specialization constant to build
7238
John Kessenichd94c0032016-05-30 19:29:40 -06007239 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007240 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7241 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7242 std::vector<spv::Id> dimConstId;
7243 for (int dim = 0; dim < 3; ++dim) {
7244 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7245 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007246 if (specConst) {
7247 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7248 glslangIntermediate->getLocalSizeSpecId(dim));
7249 }
qining4f4bb812016-04-03 23:55:17 -04007250 }
7251 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7252 }
7253
7254 // An AST node labelled as specialization constant should be a symbol node.
7255 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7256 if (auto* sn = node.getAsSymbolNode()) {
7257 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007258 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7259 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7260 // will set the builder into spec constant op instruction generating mode.
7261 sub_tree->traverse(this);
7262 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04007263 } else if (auto* const_union_array = &sn->getConstArray()){
7264 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01007265 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
7266 builder.addName(id, sn->getName().c_str());
7267 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07007268 }
7269 }
qining4f4bb812016-04-03 23:55:17 -04007270
7271 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7272 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007273 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007274 exit(1);
7275 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007276}
7277
John Kessenich140f3df2015-06-26 16:58:36 -06007278// Use 'consts' as the flattened glslang source of scalar constants to recursively
7279// build the aggregate SPIR-V constant.
7280//
7281// If there are not enough elements present in 'consts', 0 will be substituted;
7282// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7283//
qining08408382016-03-21 09:51:37 -04007284spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007285{
7286 // vector of constants for SPIR-V
7287 std::vector<spv::Id> spvConsts;
7288
7289 // Type is used for struct and array constants
7290 spv::Id typeId = convertGlslangToSpvType(glslangType);
7291
7292 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007293 glslang::TType elementType(glslangType, 0);
7294 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007295 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007296 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007297 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007298 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007299 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007300 } else if (glslangType.getStruct()) {
7301 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7302 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007303 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007304 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007305 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7306 bool zero = nextConst >= consts.size();
7307 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007308 case glslang::EbtInt8:
7309 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7310 break;
7311 case glslang::EbtUint8:
7312 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7313 break;
7314 case glslang::EbtInt16:
7315 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7316 break;
7317 case glslang::EbtUint16:
7318 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7319 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007320 case glslang::EbtInt:
7321 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7322 break;
7323 case glslang::EbtUint:
7324 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7325 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007326 case glslang::EbtInt64:
7327 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7328 break;
7329 case glslang::EbtUint64:
7330 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7331 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007332 case glslang::EbtFloat:
7333 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7334 break;
7335 case glslang::EbtDouble:
7336 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7337 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007338 case glslang::EbtFloat16:
7339 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7340 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007341 case glslang::EbtBool:
7342 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7343 break;
7344 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007346 break;
7347 }
7348 ++nextConst;
7349 }
7350 } else {
7351 // we have a non-aggregate (scalar) constant
7352 bool zero = nextConst >= consts.size();
7353 spv::Id scalar = 0;
7354 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007355 case glslang::EbtInt8:
7356 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7357 break;
7358 case glslang::EbtUint8:
7359 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7360 break;
7361 case glslang::EbtInt16:
7362 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7363 break;
7364 case glslang::EbtUint16:
7365 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7366 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007367 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007368 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007369 break;
7370 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007371 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007372 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007373 case glslang::EbtInt64:
7374 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7375 break;
7376 case glslang::EbtUint64:
7377 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7378 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007379 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007380 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007381 break;
7382 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007383 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007384 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007385 case glslang::EbtFloat16:
7386 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7387 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007388 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007389 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007390 break;
7391 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007392 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007393 break;
7394 }
7395 ++nextConst;
7396 return scalar;
7397 }
7398
7399 return builder.makeCompositeConstant(typeId, spvConsts);
7400}
7401
John Kessenich7c1aa102015-10-15 13:29:11 -06007402// Return true if the node is a constant or symbol whose reading has no
7403// non-trivial observable cost or effect.
7404bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7405{
7406 // don't know what this is
7407 if (node == nullptr)
7408 return false;
7409
7410 // a constant is safe
7411 if (node->getAsConstantUnion() != nullptr)
7412 return true;
7413
7414 // not a symbol means non-trivial
7415 if (node->getAsSymbolNode() == nullptr)
7416 return false;
7417
7418 // a symbol, depends on what's being read
7419 switch (node->getType().getQualifier().storage) {
7420 case glslang::EvqTemporary:
7421 case glslang::EvqGlobal:
7422 case glslang::EvqIn:
7423 case glslang::EvqInOut:
7424 case glslang::EvqConst:
7425 case glslang::EvqConstReadOnly:
7426 case glslang::EvqUniform:
7427 return true;
7428 default:
7429 return false;
7430 }
qining25262b32016-05-06 17:25:16 -04007431}
John Kessenich7c1aa102015-10-15 13:29:11 -06007432
7433// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007434// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007435// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007436// Return true if trivial.
7437bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7438{
7439 if (node == nullptr)
7440 return false;
7441
John Kessenich84cc15f2017-05-24 16:44:47 -06007442 // count non scalars as trivial, as well as anything coming from HLSL
7443 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007444 return true;
7445
John Kessenich7c1aa102015-10-15 13:29:11 -06007446 // symbols and constants are trivial
7447 if (isTrivialLeaf(node))
7448 return true;
7449
7450 // otherwise, it needs to be a simple operation or one or two leaf nodes
7451
7452 // not a simple operation
7453 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7454 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7455 if (binaryNode == nullptr && unaryNode == nullptr)
7456 return false;
7457
7458 // not on leaf nodes
7459 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7460 return false;
7461
7462 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7463 return false;
7464 }
7465
7466 switch (node->getAsOperator()->getOp()) {
7467 case glslang::EOpLogicalNot:
7468 case glslang::EOpConvIntToBool:
7469 case glslang::EOpConvUintToBool:
7470 case glslang::EOpConvFloatToBool:
7471 case glslang::EOpConvDoubleToBool:
7472 case glslang::EOpEqual:
7473 case glslang::EOpNotEqual:
7474 case glslang::EOpLessThan:
7475 case glslang::EOpGreaterThan:
7476 case glslang::EOpLessThanEqual:
7477 case glslang::EOpGreaterThanEqual:
7478 case glslang::EOpIndexDirect:
7479 case glslang::EOpIndexDirectStruct:
7480 case glslang::EOpLogicalXor:
7481 case glslang::EOpAny:
7482 case glslang::EOpAll:
7483 return true;
7484 default:
7485 return false;
7486 }
7487}
7488
7489// Emit short-circuiting code, where 'right' is never evaluated unless
7490// the left side is true (for &&) or false (for ||).
7491spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7492{
7493 spv::Id boolTypeId = builder.makeBoolType();
7494
7495 // emit left operand
7496 builder.clearAccessChain();
7497 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007498 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007499
7500 // Operands to accumulate OpPhi operands
7501 std::vector<spv::Id> phiOperands;
7502 // accumulate left operand's phi information
7503 phiOperands.push_back(leftId);
7504 phiOperands.push_back(builder.getBuildPoint()->getId());
7505
7506 // Make the two kinds of operation symmetric with a "!"
7507 // || => emit "if (! left) result = right"
7508 // && => emit "if ( left) result = right"
7509 //
7510 // TODO: this runtime "not" for || could be avoided by adding functionality
7511 // to 'builder' to have an "else" without an "then"
7512 if (op == glslang::EOpLogicalOr)
7513 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7514
7515 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007516 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007517
7518 // emit right operand as the "then" part of the "if"
7519 builder.clearAccessChain();
7520 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007521 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007522
7523 // accumulate left operand's phi information
7524 phiOperands.push_back(rightId);
7525 phiOperands.push_back(builder.getBuildPoint()->getId());
7526
7527 // finish the "if"
7528 ifBuilder.makeEndIf();
7529
7530 // phi together the two results
7531 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7532}
7533
Frank Henigman541f7bb2018-01-16 00:18:26 -05007534#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007535// Return type Id of the imported set of extended instructions corresponds to the name.
7536// Import this set if it has not been imported yet.
7537spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7538{
7539 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7540 return extBuiltinMap[name];
7541 else {
Rex Xu51596642016-09-21 18:56:12 +08007542 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007543 spv::Id extBuiltins = builder.import(name);
7544 extBuiltinMap[name] = extBuiltins;
7545 return extBuiltins;
7546 }
7547}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007548#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007549
John Kessenich140f3df2015-06-26 16:58:36 -06007550}; // end anonymous namespace
7551
7552namespace glslang {
7553
John Kessenich68d78fd2015-07-12 19:28:10 -06007554void GetSpirvVersion(std::string& version)
7555{
John Kessenich9e55f632015-07-15 10:03:39 -06007556 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007557 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007558 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007559 version = buf;
7560}
7561
John Kessenicha372a3e2017-11-02 22:32:14 -06007562// For low-order part of the generator's magic number. Bump up
7563// when there is a change in the style (e.g., if SSA form changes,
7564// or a different instruction sequence to do something gets used).
7565int GetSpirvGeneratorVersion()
7566{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007567 // return 1; // start
7568 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007569 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007570 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007571 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007572 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7573 // versions 4 and 6 each generate OpArrayLength as it has long been done
7574 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007575}
7576
John Kessenich140f3df2015-06-26 16:58:36 -06007577// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007578void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007579{
7580 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007581 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007582 if (out.fail())
7583 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007584 for (int i = 0; i < (int)spirv.size(); ++i) {
7585 unsigned int word = spirv[i];
7586 out.write((const char*)&word, 4);
7587 }
7588 out.close();
7589}
7590
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007591// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007592void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007593{
7594 std::ofstream out;
7595 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007596 if (out.fail())
7597 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007598 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007599 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007600 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007601 if (varName != nullptr) {
7602 out << "\t #pragma once" << std::endl;
7603 out << "const uint32_t " << varName << "[] = {" << std::endl;
7604 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007605 const int WORDS_PER_LINE = 8;
7606 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7607 out << "\t";
7608 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7609 const unsigned int word = spirv[i + j];
7610 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7611 if (i + j + 1 < (int)spirv.size()) {
7612 out << ",";
7613 }
7614 }
7615 out << std::endl;
7616 }
Flavio15017db2017-02-15 14:29:33 -08007617 if (varName != nullptr) {
7618 out << "};";
7619 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007620 out.close();
7621}
7622
John Kessenich140f3df2015-06-26 16:58:36 -06007623//
7624// Set up the glslang traversal
7625//
John Kessenich4e11b612018-08-30 16:56:59 -06007626void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007627{
Lei Zhang17535f72016-05-04 15:55:59 -04007628 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007629 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007630}
7631
John Kessenich4e11b612018-08-30 16:56:59 -06007632void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007633 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007634{
John Kessenich140f3df2015-06-26 16:58:36 -06007635 TIntermNode* root = intermediate.getTreeRoot();
7636
7637 if (root == 0)
7638 return;
7639
John Kessenich4e11b612018-08-30 16:56:59 -06007640 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007641 if (options == nullptr)
7642 options = &defaultOptions;
7643
John Kessenich4e11b612018-08-30 16:56:59 -06007644 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007645
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007646 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007647 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007648 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007649 it.dumpSpv(spirv);
7650
GregFfb03a552018-03-29 11:49:14 -06007651#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007652 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7653 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007654 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007655 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007656
John Kessenich4e11b612018-08-30 16:56:59 -06007657 if (options->validate)
7658 SpirvToolsValidate(intermediate, spirv, logger);
7659
John Kessenich717c80a2018-08-23 15:17:10 -06007660 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007661 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007662
GregFcd1f1692017-09-21 18:40:22 -06007663#endif
7664
John Kessenich4e11b612018-08-30 16:56:59 -06007665 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007666}
7667
7668}; // end namespace glslang