blob: 6dc25ab1e5be01f86c6c15802c3ef56c0c0aff0a [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
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
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
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;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
559 // *coherent variables are implicitly nonprivate in GLSL
560 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500561 flags.subgroupcoherent ||
562 flags.workgroupcoherent ||
563 flags.queuefamilycoherent ||
564 flags.devicecoherent ||
565 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500566 flags.volatil = type.getQualifier().volatil;
567 flags.isImage = type.getBasicType() == glslang::EbtSampler;
568 return flags;
569}
570
571spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
572{
573 spv::Scope scope;
574 if (coherentFlags.coherent) {
575 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
576 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
577 } else if (coherentFlags.devicecoherent) {
578 scope = spv::ScopeDevice;
579 } else if (coherentFlags.queuefamilycoherent) {
580 scope = spv::ScopeQueueFamilyKHR;
581 } else if (coherentFlags.workgroupcoherent) {
582 scope = spv::ScopeWorkgroup;
583 } else if (coherentFlags.subgroupcoherent) {
584 scope = spv::ScopeSubgroup;
585 } else {
586 scope = spv::ScopeMax;
587 }
588 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
589 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
590 }
591 return scope;
592}
593
David Netoa901ffe2016-06-08 14:11:40 +0100594// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
595// associated capabilities when required. For some built-in variables, a capability
596// is generated only when using the variable in an executable instruction, but not when
597// just declaring a struct member variable with it. This is true for PointSize,
598// ClipDistance, and CullDistance.
599spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600600{
601 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700602 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600603 // Defer adding the capability until the built-in is actually used.
604 if (! memberDeclaration) {
605 switch (glslangIntermediate->getStage()) {
606 case EShLangGeometry:
607 builder.addCapability(spv::CapabilityGeometryPointSize);
608 break;
609 case EShLangTessControl:
610 case EShLangTessEvaluation:
611 builder.addCapability(spv::CapabilityTessellationPointSize);
612 break;
613 default:
614 break;
615 }
John Kessenich92187592016-02-01 13:45:25 -0700616 }
617 return spv::BuiltInPointSize;
618
John Kessenichebb50532016-05-16 19:22:05 -0600619 // These *Distance capabilities logically belong here, but if the member is declared and
620 // then never used, consumers of SPIR-V prefer the capability not be declared.
621 // They are now generated when used, rather than here when declared.
622 // Potentially, the specification should be more clear what the minimum
623 // use needed is to trigger the capability.
624 //
John Kessenich92187592016-02-01 13:45:25 -0700625 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100626 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800627 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700628 return spv::BuiltInClipDistance;
629
630 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100631 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800632 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700633 return spv::BuiltInCullDistance;
634
635 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600636 builder.addCapability(spv::CapabilityMultiViewport);
637 if (glslangIntermediate->getStage() == EShLangVertex ||
638 glslangIntermediate->getStage() == EShLangTessControl ||
639 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800640
John Kessenichba6a3c22017-09-13 13:22:50 -0600641 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
642 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800643 }
John Kessenich92187592016-02-01 13:45:25 -0700644 return spv::BuiltInViewportIndex;
645
John Kessenich5e801132016-02-15 11:09:46 -0700646 case glslang::EbvSampleId:
647 builder.addCapability(spv::CapabilitySampleRateShading);
648 return spv::BuiltInSampleId;
649
650 case glslang::EbvSamplePosition:
651 builder.addCapability(spv::CapabilitySampleRateShading);
652 return spv::BuiltInSamplePosition;
653
654 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700655 return spv::BuiltInSampleMask;
656
John Kessenich78a45572016-07-08 14:05:15 -0600657 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700658#ifdef NV_EXTENSIONS
659 if (glslangIntermediate->getStage() == EShLangMeshNV) {
660 return spv::BuiltInLayer;
661 }
662#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600663 builder.addCapability(spv::CapabilityGeometry);
664 if (glslangIntermediate->getStage() == EShLangVertex ||
665 glslangIntermediate->getStage() == EShLangTessControl ||
666 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800667
John Kessenichba6a3c22017-09-13 13:22:50 -0600668 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
669 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800670 }
John Kessenich78a45572016-07-08 14:05:15 -0600671 return spv::BuiltInLayer;
672
John Kessenich140f3df2015-06-26 16:58:36 -0600673 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvVertexId: return spv::BuiltInVertexId;
675 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700676 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
677 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800678
John Kessenichda581a22015-10-14 14:10:30 -0600679 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700680 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800681 builder.addCapability(spv::CapabilityDrawParameters);
682 return spv::BuiltInBaseVertex;
683
John Kessenichda581a22015-10-14 14:10:30 -0600684 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700685 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800686 builder.addCapability(spv::CapabilityDrawParameters);
687 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200688
John Kessenichda581a22015-10-14 14:10:30 -0600689 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800691 builder.addCapability(spv::CapabilityDrawParameters);
692 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200693
694 case glslang::EbvPrimitiveId:
695 if (glslangIntermediate->getStage() == EShLangFragment)
696 builder.addCapability(spv::CapabilityGeometry);
697 return spv::BuiltInPrimitiveId;
698
Rex Xu37cdcee2017-06-29 17:46:34 +0800699 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800700 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
701 builder.addCapability(spv::CapabilityStencilExportEXT);
702 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800703
John Kessenich140f3df2015-06-26 16:58:36 -0600704 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
706 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
707 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
708 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
709 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
710 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
711 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600712 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
713 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
714 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
715 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
716 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
717 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
718 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
719 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800720
Rex Xu574ab042016-04-14 16:53:07 +0800721 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800722 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800723 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
724 return spv::BuiltInSubgroupSize;
725
Rex Xu574ab042016-04-14 16:53:07 +0800726 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800727 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800728 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
729 return spv::BuiltInSubgroupLocalInvocationId;
730
Rex Xu574ab042016-04-14 16:53:07 +0800731 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800732 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
733 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
734 return spv::BuiltInSubgroupEqMaskKHR;
735
Rex Xu574ab042016-04-14 16:53:07 +0800736 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800737 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
738 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
739 return spv::BuiltInSubgroupGeMaskKHR;
740
Rex Xu574ab042016-04-14 16:53:07 +0800741 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800742 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
743 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
744 return spv::BuiltInSubgroupGtMaskKHR;
745
Rex Xu574ab042016-04-14 16:53:07 +0800746 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800747 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
748 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
749 return spv::BuiltInSubgroupLeMaskKHR;
750
Rex Xu574ab042016-04-14 16:53:07 +0800751 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800752 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
753 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
754 return spv::BuiltInSubgroupLtMaskKHR;
755
John Kessenich66011cb2018-03-06 16:12:04 -0700756 case glslang::EbvNumSubgroups:
757 builder.addCapability(spv::CapabilityGroupNonUniform);
758 return spv::BuiltInNumSubgroups;
759
760 case glslang::EbvSubgroupID:
761 builder.addCapability(spv::CapabilityGroupNonUniform);
762 return spv::BuiltInSubgroupId;
763
764 case glslang::EbvSubgroupSize2:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInSubgroupSize;
767
768 case glslang::EbvSubgroupInvocation2:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 return spv::BuiltInSubgroupLocalInvocationId;
771
772 case glslang::EbvSubgroupEqMask2:
773 builder.addCapability(spv::CapabilityGroupNonUniform);
774 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
775 return spv::BuiltInSubgroupEqMask;
776
777 case glslang::EbvSubgroupGeMask2:
778 builder.addCapability(spv::CapabilityGroupNonUniform);
779 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
780 return spv::BuiltInSubgroupGeMask;
781
782 case glslang::EbvSubgroupGtMask2:
783 builder.addCapability(spv::CapabilityGroupNonUniform);
784 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
785 return spv::BuiltInSubgroupGtMask;
786
787 case glslang::EbvSubgroupLeMask2:
788 builder.addCapability(spv::CapabilityGroupNonUniform);
789 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
790 return spv::BuiltInSubgroupLeMask;
791
792 case glslang::EbvSubgroupLtMask2:
793 builder.addCapability(spv::CapabilityGroupNonUniform);
794 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
795 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800797 case glslang::EbvBaryCoordNoPersp:
798 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
799 return spv::BuiltInBaryCoordNoPerspAMD;
800
801 case glslang::EbvBaryCoordNoPerspCentroid:
802 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
803 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
804
805 case glslang::EbvBaryCoordNoPerspSample:
806 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
807 return spv::BuiltInBaryCoordNoPerspSampleAMD;
808
809 case glslang::EbvBaryCoordSmooth:
810 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
811 return spv::BuiltInBaryCoordSmoothAMD;
812
813 case glslang::EbvBaryCoordSmoothCentroid:
814 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
815 return spv::BuiltInBaryCoordSmoothCentroidAMD;
816
817 case glslang::EbvBaryCoordSmoothSample:
818 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
819 return spv::BuiltInBaryCoordSmoothSampleAMD;
820
821 case glslang::EbvBaryCoordPullModel:
822 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
823 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800824#endif
chaoc771d89f2017-01-13 01:10:53 -0800825
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700827 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700828 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700829 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700830
831 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700832 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700833 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700834 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835
Daniel Koch5154db52018-11-26 10:01:58 -0500836 case glslang::EbvFragSizeEXT:
837 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
838 builder.addCapability(spv::CapabilityFragmentDensityEXT);
839 return spv::BuiltInFragSizeEXT;
840
841 case glslang::EbvFragInvocationCountEXT:
842 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
843 builder.addCapability(spv::CapabilityFragmentDensityEXT);
844 return spv::BuiltInFragInvocationCountEXT;
845
chaoc771d89f2017-01-13 01:10:53 -0800846#ifdef NV_EXTENSIONS
847 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800848 if (!memberDeclaration) {
849 builder.addExtension(spv::E_SPV_NV_viewport_array2);
850 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
851 }
chaoc771d89f2017-01-13 01:10:53 -0800852 return spv::BuiltInViewportMaskNV;
853 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800854 if (!memberDeclaration) {
855 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
856 builder.addCapability(spv::CapabilityShaderStereoViewNV);
857 }
chaoc771d89f2017-01-13 01:10:53 -0800858 return spv::BuiltInSecondaryPositionNV;
859 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800860 if (!memberDeclaration) {
861 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
862 builder.addCapability(spv::CapabilityShaderStereoViewNV);
863 }
chaoc771d89f2017-01-13 01:10:53 -0800864 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800865 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800866 if (!memberDeclaration) {
867 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
868 builder.addCapability(spv::CapabilityPerViewAttributesNV);
869 }
chaocdf3956c2017-02-14 14:52:34 -0800870 return spv::BuiltInPositionPerViewNV;
871 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800872 if (!memberDeclaration) {
873 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
874 builder.addCapability(spv::CapabilityPerViewAttributesNV);
875 }
chaocdf3956c2017-02-14 14:52:34 -0800876 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700877 case glslang::EbvFragFullyCoveredNV:
878 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
879 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
880 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700881 case glslang::EbvFragmentSizeNV:
882 builder.addExtension(spv::E_SPV_NV_shading_rate);
883 builder.addCapability(spv::CapabilityShadingRateNV);
884 return spv::BuiltInFragmentSizeNV;
885 case glslang::EbvInvocationsPerPixelNV:
886 builder.addExtension(spv::E_SPV_NV_shading_rate);
887 builder.addCapability(spv::CapabilityShadingRateNV);
888 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700889
890 // raytracing
891 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700892 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700893 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700894 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700895 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700896 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700897 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700898 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700900 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInWorldToObjectNV;
917 case glslang::EbvIncomingRayFlagsNV:
918 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700919 case glslang::EbvBaryCoordNV:
920 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
921 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
922 return spv::BuiltInBaryCoordNV;
923 case glslang::EbvBaryCoordNoPerspNV:
924 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
925 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
926 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700927 case glslang::EbvTaskCountNV:
928 return spv::BuiltInTaskCountNV;
929 case glslang::EbvPrimitiveCountNV:
930 return spv::BuiltInPrimitiveCountNV;
931 case glslang::EbvPrimitiveIndicesNV:
932 return spv::BuiltInPrimitiveIndicesNV;
933 case glslang::EbvClipDistancePerViewNV:
934 return spv::BuiltInClipDistancePerViewNV;
935 case glslang::EbvCullDistancePerViewNV:
936 return spv::BuiltInCullDistancePerViewNV;
937 case glslang::EbvLayerPerViewNV:
938 return spv::BuiltInLayerPerViewNV;
939 case glslang::EbvMeshViewCountNV:
940 return spv::BuiltInMeshViewCountNV;
941 case glslang::EbvMeshViewIndicesNV:
942 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800943#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800944 default:
945 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600946 }
947}
948
Rex Xufc618912015-09-09 16:42:49 +0800949// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700950spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800951{
952 assert(type.getBasicType() == glslang::EbtSampler);
953
John Kessenich5d0fa972016-02-15 11:57:00 -0700954 // Check for capabilities
955 switch (type.getQualifier().layoutFormat) {
956 case glslang::ElfRg32f:
957 case glslang::ElfRg16f:
958 case glslang::ElfR11fG11fB10f:
959 case glslang::ElfR16f:
960 case glslang::ElfRgba16:
961 case glslang::ElfRgb10A2:
962 case glslang::ElfRg16:
963 case glslang::ElfRg8:
964 case glslang::ElfR16:
965 case glslang::ElfR8:
966 case glslang::ElfRgba16Snorm:
967 case glslang::ElfRg16Snorm:
968 case glslang::ElfRg8Snorm:
969 case glslang::ElfR16Snorm:
970 case glslang::ElfR8Snorm:
971
972 case glslang::ElfRg32i:
973 case glslang::ElfRg16i:
974 case glslang::ElfRg8i:
975 case glslang::ElfR16i:
976 case glslang::ElfR8i:
977
978 case glslang::ElfRgb10a2ui:
979 case glslang::ElfRg32ui:
980 case glslang::ElfRg16ui:
981 case glslang::ElfRg8ui:
982 case glslang::ElfR16ui:
983 case glslang::ElfR8ui:
984 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
985 break;
986
987 default:
988 break;
989 }
990
991 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800992 switch (type.getQualifier().layoutFormat) {
993 case glslang::ElfNone: return spv::ImageFormatUnknown;
994 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
995 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
996 case glslang::ElfR32f: return spv::ImageFormatR32f;
997 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
998 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
999 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1000 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1001 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1002 case glslang::ElfR16f: return spv::ImageFormatR16f;
1003 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1004 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1005 case glslang::ElfRg16: return spv::ImageFormatRg16;
1006 case glslang::ElfRg8: return spv::ImageFormatRg8;
1007 case glslang::ElfR16: return spv::ImageFormatR16;
1008 case glslang::ElfR8: return spv::ImageFormatR8;
1009 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1010 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1011 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1012 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1013 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1014 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1015 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1016 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1017 case glslang::ElfR32i: return spv::ImageFormatR32i;
1018 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1019 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1020 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1021 case glslang::ElfR16i: return spv::ImageFormatR16i;
1022 case glslang::ElfR8i: return spv::ImageFormatR8i;
1023 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1024 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1025 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1026 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1027 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1028 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1029 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1030 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1031 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1032 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001033 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001034 }
1035}
1036
John Kesseniche18fd202018-01-30 11:01:39 -07001037spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001038{
John Kesseniche18fd202018-01-30 11:01:39 -07001039 if (selectionNode.getFlatten())
1040 return spv::SelectionControlFlattenMask;
1041 if (selectionNode.getDontFlatten())
1042 return spv::SelectionControlDontFlattenMask;
1043 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001044}
1045
John Kesseniche18fd202018-01-30 11:01:39 -07001046spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001047{
John Kesseniche18fd202018-01-30 11:01:39 -07001048 if (switchNode.getFlatten())
1049 return spv::SelectionControlFlattenMask;
1050 if (switchNode.getDontFlatten())
1051 return spv::SelectionControlDontFlattenMask;
1052 return spv::SelectionControlMaskNone;
1053}
1054
John Kessenicha2858d92018-01-31 08:11:18 -07001055// return a non-0 dependency if the dependency argument must be set
1056spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1057 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001058{
1059 spv::LoopControlMask control = spv::LoopControlMaskNone;
1060
1061 if (loopNode.getDontUnroll())
1062 control = control | spv::LoopControlDontUnrollMask;
1063 if (loopNode.getUnroll())
1064 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001065 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001066 control = control | spv::LoopControlDependencyInfiniteMask;
1067 else if (loopNode.getLoopDependency() > 0) {
1068 control = control | spv::LoopControlDependencyLengthMask;
1069 dependencyLength = loopNode.getLoopDependency();
1070 }
John Kesseniche18fd202018-01-30 11:01:39 -07001071
1072 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001073}
1074
John Kessenicha5c5fb62017-05-05 05:09:58 -06001075// Translate glslang type to SPIR-V storage class.
1076spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1077{
1078 if (type.getQualifier().isPipeInput())
1079 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001080 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001081 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001082
1083 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1084 type.getQualifier().storage == glslang::EvqUniform) {
1085 if (type.getBasicType() == glslang::EbtAtomicUint)
1086 return spv::StorageClassAtomicCounter;
1087 if (type.containsOpaque())
1088 return spv::StorageClassUniformConstant;
1089 }
1090
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001091#ifdef NV_EXTENSIONS
1092 if (type.getQualifier().isUniformOrBuffer() &&
1093 type.getQualifier().layoutShaderRecordNV) {
1094 return spv::StorageClassShaderRecordBufferNV;
1095 }
1096#endif
1097
John Kessenichbed4e4f2017-09-08 02:38:07 -06001098 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001099 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001100 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001101 }
1102
1103 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001104 if (type.getQualifier().layoutPushConstant)
1105 return spv::StorageClassPushConstant;
1106 if (type.getBasicType() == glslang::EbtBlock)
1107 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001108 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001109 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001110
1111 switch (type.getQualifier().storage) {
1112 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1113 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1114 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1115 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001116#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001117 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1118 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1119 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1120 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1121 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001122#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001123 default:
1124 assert(0);
1125 break;
1126 }
1127
1128 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001129}
1130
John Kessenich5611c6d2018-04-05 11:25:02 -06001131// Add capabilities pertaining to how an array is indexed.
1132void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1133 const glslang::TType& indexType)
1134{
1135 if (indexType.getQualifier().isNonUniform()) {
1136 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001137 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001138 if (baseType.getBasicType() == glslang::EbtSampler) {
1139 if (baseType.getQualifier().hasAttachment())
1140 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1141 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1142 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1143 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1144 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1145 else if (baseType.isImage())
1146 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1147 else if (baseType.isTexture())
1148 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1149 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1150 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1151 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1152 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1153 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1154 }
1155 } else {
1156 // assume a dynamically uniform index
1157 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001158 if (baseType.getQualifier().hasAttachment()) {
1159 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001160 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001161 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1162 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001163 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001164 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1165 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001166 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001167 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001168 }
1169 }
1170}
1171
qining25262b32016-05-06 17:25:16 -04001172// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001173// descriptor set.
1174bool IsDescriptorResource(const glslang::TType& type)
1175{
John Kessenichf7497e22016-03-08 21:36:22 -07001176 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001177 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001178 return type.getQualifier().isUniformOrBuffer() &&
1179#ifdef NV_EXTENSIONS
1180 ! type.getQualifier().layoutShaderRecordNV &&
1181#endif
1182 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001183
1184 // non block...
1185 // basically samplerXXX/subpass/sampler/texture are all included
1186 // if they are the global-scope-class, not the function parameter
1187 // (or local, if they ever exist) class.
1188 if (type.getBasicType() == glslang::EbtSampler)
1189 return type.getQualifier().isUniformOrBuffer();
1190
1191 // None of the above.
1192 return false;
1193}
1194
John Kesseniche0b6cad2015-12-24 10:30:13 -07001195void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1196{
1197 if (child.layoutMatrix == glslang::ElmNone)
1198 child.layoutMatrix = parent.layoutMatrix;
1199
1200 if (parent.invariant)
1201 child.invariant = true;
1202 if (parent.nopersp)
1203 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001204#ifdef AMD_EXTENSIONS
1205 if (parent.explicitInterp)
1206 child.explicitInterp = true;
1207#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001208 if (parent.flat)
1209 child.flat = true;
1210 if (parent.centroid)
1211 child.centroid = true;
1212 if (parent.patch)
1213 child.patch = true;
1214 if (parent.sample)
1215 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001216 if (parent.coherent)
1217 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001218 if (parent.devicecoherent)
1219 child.devicecoherent = true;
1220 if (parent.queuefamilycoherent)
1221 child.queuefamilycoherent = true;
1222 if (parent.workgroupcoherent)
1223 child.workgroupcoherent = true;
1224 if (parent.subgroupcoherent)
1225 child.subgroupcoherent = true;
1226 if (parent.nonprivate)
1227 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001228 if (parent.volatil)
1229 child.volatil = true;
1230 if (parent.restrict)
1231 child.restrict = true;
1232 if (parent.readonly)
1233 child.readonly = true;
1234 if (parent.writeonly)
1235 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001236#ifdef NV_EXTENSIONS
1237 if (parent.perPrimitiveNV)
1238 child.perPrimitiveNV = true;
1239 if (parent.perViewNV)
1240 child.perViewNV = true;
1241 if (parent.perTaskNV)
1242 child.perTaskNV = true;
1243#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001244}
1245
John Kessenichf2b7f332016-09-01 17:05:23 -06001246bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001247{
John Kessenich7b9fa252016-01-21 18:56:57 -07001248 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001249 // - struct members might inherit from a struct declaration
1250 // (note that non-block structs don't explicitly inherit,
1251 // only implicitly, meaning no decoration involved)
1252 // - affect decorations on the struct members
1253 // (note smooth does not, and expecting something like volatile
1254 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001255 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001256 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001257}
1258
John Kessenich140f3df2015-06-26 16:58:36 -06001259//
1260// Implement the TGlslangToSpvTraverser class.
1261//
1262
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001263TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001264 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1265 : TIntermTraverser(true, false, true),
1266 options(options),
1267 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001268 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001269 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001270 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001271 glslangIntermediate(glslangIntermediate)
1272{
1273 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1274
1275 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001276 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1277 glslangIntermediate->getVersion());
1278
John Kessenich121853f2017-05-31 17:11:16 -06001279 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001280 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001281 builder.setSourceFile(glslangIntermediate->getSourceFile());
1282
1283 // Set the source shader's text. If for SPV version 1.0, include
1284 // a preamble in comments stating the OpModuleProcessed instructions.
1285 // Otherwise, emit those as actual instructions.
1286 std::string text;
1287 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1288 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001289 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001290 text.append("// OpModuleProcessed ");
1291 text.append(processes[p]);
1292 text.append("\n");
1293 } else
1294 builder.addModuleProcessed(processes[p]);
1295 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001296 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001297 text.append("#line 1\n");
1298 text.append(glslangIntermediate->getSourceText());
1299 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001300 // Pass name and text for all included files
1301 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1302 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1303 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001304 }
John Kessenich140f3df2015-06-26 16:58:36 -06001305 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001306 if (glslangIntermediate->usingVulkanMemoryModel()) {
1307 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1308 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1309 } else {
1310 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1311 }
John Kessenicheee9d532016-09-19 18:09:30 -06001312 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1313 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001314
1315 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001316 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1317 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001318 builder.addSourceExtension(it->c_str());
1319
1320 // Add the top-level modes for this shader.
1321
John Kessenich92187592016-02-01 13:45:25 -07001322 if (glslangIntermediate->getXfbMode()) {
1323 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001324 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001325 }
John Kessenich140f3df2015-06-26 16:58:36 -06001326
1327 unsigned int mode;
1328 switch (glslangIntermediate->getStage()) {
1329 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001330 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001331 break;
1332
steve-lunarge7412492017-03-23 11:56:07 -06001333 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001334 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001335 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001336
steve-lunarge7412492017-03-23 11:56:07 -06001337 glslang::TLayoutGeometry primitive;
1338
1339 if (glslangIntermediate->getStage() == EShLangTessControl) {
1340 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1341 primitive = glslangIntermediate->getOutputPrimitive();
1342 } else {
1343 primitive = glslangIntermediate->getInputPrimitive();
1344 }
1345
1346 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001347 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1348 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1349 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001350 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001351 }
John Kessenich4016e382016-07-15 11:53:56 -06001352 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001353 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1354
John Kesseniche6903322015-10-13 16:29:02 -06001355 switch (glslangIntermediate->getVertexSpacing()) {
1356 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1357 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1358 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001359 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001360 }
John Kessenich4016e382016-07-15 11:53:56 -06001361 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001362 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1363
1364 switch (glslangIntermediate->getVertexOrder()) {
1365 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1366 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001367 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001368 }
John Kessenich4016e382016-07-15 11:53:56 -06001369 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001370 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1371
1372 if (glslangIntermediate->getPointMode())
1373 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001374 break;
1375
1376 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001377 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001378 switch (glslangIntermediate->getInputPrimitive()) {
1379 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1380 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1381 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001382 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001383 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001384 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001385 }
John Kessenich4016e382016-07-15 11:53:56 -06001386 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001387 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001388
John Kessenich140f3df2015-06-26 16:58:36 -06001389 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1390
1391 switch (glslangIntermediate->getOutputPrimitive()) {
1392 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1393 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1394 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001395 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001396 }
John Kessenich4016e382016-07-15 11:53:56 -06001397 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001398 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1399 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1400 break;
1401
1402 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001403 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001404 if (glslangIntermediate->getPixelCenterInteger())
1405 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001406
John Kessenich140f3df2015-06-26 16:58:36 -06001407 if (glslangIntermediate->getOriginUpperLeft())
1408 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001409 else
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001411
1412 if (glslangIntermediate->getEarlyFragmentTests())
1413 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1414
chaocc1204522017-06-30 17:14:30 -07001415 if (glslangIntermediate->getPostDepthCoverage()) {
1416 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1417 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1418 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1419 }
1420
John Kesseniche6903322015-10-13 16:29:02 -06001421 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001422 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1423 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001424 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001425 }
John Kessenich4016e382016-07-15 11:53:56 -06001426 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001427 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1428
1429 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1430 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 break;
1432
1433 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001434 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1436 glslangIntermediate->getLocalSize(1),
1437 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001438#ifdef NV_EXTENSIONS
1439 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1440 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1442 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1443 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1444 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1446 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1447 }
1448#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001449 break;
1450
Chao Chen3c366992018-09-19 11:41:59 -07001451#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001452 case EShLangRayGenNV:
1453 case EShLangIntersectNV:
1454 case EShLangAnyHitNV:
1455 case EShLangClosestHitNV:
1456 case EShLangMissNV:
1457 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001458 builder.addCapability(spv::CapabilityRayTracingNV);
1459 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001460 break;
Chao Chen3c366992018-09-19 11:41:59 -07001461 case EShLangTaskNV:
1462 case EShLangMeshNV:
1463 builder.addCapability(spv::CapabilityMeshShadingNV);
1464 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1466 glslangIntermediate->getLocalSize(1),
1467 glslangIntermediate->getLocalSize(2));
1468 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1471
1472 switch (glslangIntermediate->getOutputPrimitive()) {
1473 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1474 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1475 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1476 default: mode = spv::ExecutionModeMax; break;
1477 }
1478 if (mode != spv::ExecutionModeMax)
1479 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1480 }
1481 break;
1482#endif
1483
John Kessenich140f3df2015-06-26 16:58:36 -06001484 default:
1485 break;
1486 }
John Kessenich140f3df2015-06-26 16:58:36 -06001487}
1488
John Kessenichfca82622016-11-26 13:23:20 -07001489// Finish creating SPV, after the traversal is complete.
1490void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001491{
John Kessenichf04c51b2018-08-03 15:56:12 -06001492 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001493 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001494 builder.setBuildPoint(shaderEntry->getLastBlock());
1495 builder.leaveFunction();
1496 }
1497
John Kessenich7ba63412015-12-20 17:37:07 -07001498 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001499 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1500 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001501
John Kessenichf04c51b2018-08-03 15:56:12 -06001502 // Add capabilities, extensions, remove unneeded decorations, etc.,
1503 // based on the resulting SPIR-V.
1504 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001505}
1506
John Kessenichfca82622016-11-26 13:23:20 -07001507// Write the SPV into 'out'.
1508void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001509{
John Kessenichfca82622016-11-26 13:23:20 -07001510 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001511}
1512
1513//
1514// Implement the traversal functions.
1515//
1516// Return true from interior nodes to have the external traversal
1517// continue on to children. Return false if children were
1518// already processed.
1519//
1520
1521//
qining25262b32016-05-06 17:25:16 -04001522// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001523// - uniform/input reads
1524// - output writes
1525// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1526// - something simple that degenerates into the last bullet
1527//
1528void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1529{
qining75d1d802016-04-06 14:42:01 -04001530 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1531 if (symbol->getType().getQualifier().isSpecConstant())
1532 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1533
John Kessenich140f3df2015-06-26 16:58:36 -06001534 // getSymbolId() will set up all the IO decorations on the first call.
1535 // Formal function parameters were mapped during makeFunctions().
1536 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001537
1538 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1539 if (builder.isPointer(id)) {
1540 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001541 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1542 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1543 iOSet.insert(id);
1544 }
John Kessenich7ba63412015-12-20 17:37:07 -07001545 }
1546
1547 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001548 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001549 // Prepare to generate code for the access
1550
1551 // L-value chains will be computed left to right. We're on the symbol now,
1552 // which is the left-most part of the access chain, so now is "clear" time,
1553 // followed by setting the base.
1554 builder.clearAccessChain();
1555
1556 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001557 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001558 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001559 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001560 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001561 // These are also pure R-values.
1562 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001563 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001564 builder.setAccessChainRValue(id);
1565 else
1566 builder.setAccessChainLValue(id);
1567 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001568
1569 // Process linkage-only nodes for any special additional interface work.
1570 if (linkageOnly) {
1571 if (glslangIntermediate->getHlslFunctionality1()) {
1572 // Map implicit counter buffers to their originating buffers, which should have been
1573 // seen by now, given earlier pruning of unused counters, and preservation of order
1574 // of declaration.
1575 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1576 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1577 // Save possible originating buffers for counter buffers, keyed by
1578 // making the potential counter-buffer name.
1579 std::string keyName = symbol->getName().c_str();
1580 keyName = glslangIntermediate->addCounterBufferName(keyName);
1581 counterOriginator[keyName] = symbol;
1582 } else {
1583 // Handle a counter buffer, by finding the saved originating buffer.
1584 std::string keyName = symbol->getName().c_str();
1585 auto it = counterOriginator.find(keyName);
1586 if (it != counterOriginator.end()) {
1587 id = getSymbolId(it->second);
1588 if (id != spv::NoResult) {
1589 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001590 if (counterId != spv::NoResult) {
1591 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001592 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001593 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001594 }
1595 }
1596 }
1597 }
1598 }
1599 }
John Kessenich140f3df2015-06-26 16:58:36 -06001600}
1601
1602bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1603{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001604 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001605
qining40887662016-04-03 22:20:42 -04001606 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1607 if (node->getType().getQualifier().isSpecConstant())
1608 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1609
John Kessenich140f3df2015-06-26 16:58:36 -06001610 // First, handle special cases
1611 switch (node->getOp()) {
1612 case glslang::EOpAssign:
1613 case glslang::EOpAddAssign:
1614 case glslang::EOpSubAssign:
1615 case glslang::EOpMulAssign:
1616 case glslang::EOpVectorTimesMatrixAssign:
1617 case glslang::EOpVectorTimesScalarAssign:
1618 case glslang::EOpMatrixTimesScalarAssign:
1619 case glslang::EOpMatrixTimesMatrixAssign:
1620 case glslang::EOpDivAssign:
1621 case glslang::EOpModAssign:
1622 case glslang::EOpAndAssign:
1623 case glslang::EOpInclusiveOrAssign:
1624 case glslang::EOpExclusiveOrAssign:
1625 case glslang::EOpLeftShiftAssign:
1626 case glslang::EOpRightShiftAssign:
1627 // A bin-op assign "a += b" means the same thing as "a = a + b"
1628 // where a is evaluated before b. For a simple assignment, GLSL
1629 // says to evaluate the left before the right. So, always, left
1630 // node then right node.
1631 {
1632 // get the left l-value, save it away
1633 builder.clearAccessChain();
1634 node->getLeft()->traverse(this);
1635 spv::Builder::AccessChain lValue = builder.getAccessChain();
1636
1637 // evaluate the right
1638 builder.clearAccessChain();
1639 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001640 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001641
1642 if (node->getOp() != glslang::EOpAssign) {
1643 // the left is also an r-value
1644 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001645 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001646
1647 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001648 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001649 TranslateNoContractionDecoration(node->getType().getQualifier()),
1650 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001651 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001652 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1653 node->getType().getBasicType());
1654
1655 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001656 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001657 }
1658
1659 // store the result
1660 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001661 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001662
1663 // assignments are expressions having an rValue after they are evaluated...
1664 builder.clearAccessChain();
1665 builder.setAccessChainRValue(rValue);
1666 }
1667 return false;
1668 case glslang::EOpIndexDirect:
1669 case glslang::EOpIndexDirectStruct:
1670 {
1671 // Get the left part of the access chain.
1672 node->getLeft()->traverse(this);
1673
1674 // Add the next element in the chain
1675
David Netoa901ffe2016-06-08 14:11:40 +01001676 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001677 if (! node->getLeft()->getType().isArray() &&
1678 node->getLeft()->getType().isVector() &&
1679 node->getOp() == glslang::EOpIndexDirect) {
1680 // This is essentially a hard-coded vector swizzle of size 1,
1681 // so short circuit the access-chain stuff with a swizzle.
1682 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001683 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001684 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001685 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001686 int spvIndex = glslangIndex;
1687 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1688 node->getOp() == glslang::EOpIndexDirectStruct)
1689 {
1690 // This may be, e.g., an anonymous block-member selection, which generally need
1691 // index remapping due to hidden members in anonymous blocks.
1692 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1693 assert(remapper.size() > 0);
1694 spvIndex = remapper[glslangIndex];
1695 }
John Kessenichebb50532016-05-16 19:22:05 -06001696
David Netoa901ffe2016-06-08 14:11:40 +01001697 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001698 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001699
1700 // Add capabilities here for accessing PointSize and clip/cull distance.
1701 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001702 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001703 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001704 }
1705 }
1706 return false;
1707 case glslang::EOpIndexIndirect:
1708 {
1709 // Structure or array or vector indirection.
1710 // Will use native SPIR-V access-chain for struct and array indirection;
1711 // matrices are arrays of vectors, so will also work for a matrix.
1712 // Will use the access chain's 'component' for variable index into a vector.
1713
1714 // This adapter is building access chains left to right.
1715 // Set up the access chain to the left.
1716 node->getLeft()->traverse(this);
1717
1718 // save it so that computing the right side doesn't trash it
1719 spv::Builder::AccessChain partial = builder.getAccessChain();
1720
1721 // compute the next index in the chain
1722 builder.clearAccessChain();
1723 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001724 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001725
John Kessenich5611c6d2018-04-05 11:25:02 -06001726 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1727
John Kessenich140f3df2015-06-26 16:58:36 -06001728 // restore the saved access chain
1729 builder.setAccessChain(partial);
1730
1731 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001732 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001733 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001734 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001735 }
1736 return false;
1737 case glslang::EOpVectorSwizzle:
1738 {
1739 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001740 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001741 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001742 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
1744 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001745 case glslang::EOpMatrixSwizzle:
1746 logger->missingFunctionality("matrix swizzle");
1747 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001748 case glslang::EOpLogicalOr:
1749 case glslang::EOpLogicalAnd:
1750 {
1751
1752 // These may require short circuiting, but can sometimes be done as straight
1753 // binary operations. The right operand must be short circuited if it has
1754 // side effects, and should probably be if it is complex.
1755 if (isTrivial(node->getRight()->getAsTyped()))
1756 break; // handle below as a normal binary operation
1757 // otherwise, we need to do dynamic short circuiting on the right operand
1758 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1759 builder.clearAccessChain();
1760 builder.setAccessChainRValue(result);
1761 }
1762 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001763 default:
1764 break;
1765 }
1766
1767 // Assume generic binary op...
1768
John Kessenich32cfd492016-02-02 12:37:46 -07001769 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001770 builder.clearAccessChain();
1771 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001772 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001773
John Kessenich32cfd492016-02-02 12:37:46 -07001774 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001775 builder.clearAccessChain();
1776 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001777 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001778
John Kessenich32cfd492016-02-02 12:37:46 -07001779 // get result
John Kessenichead86222018-03-28 18:01:20 -06001780 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001781 TranslateNoContractionDecoration(node->getType().getQualifier()),
1782 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001783 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001784 convertGlslangToSpvType(node->getType()), left, right,
1785 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001786
John Kessenich50e57562015-12-21 21:21:11 -07001787 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001788 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001789 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001790 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001791 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001792 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001793 return false;
1794 }
John Kessenich140f3df2015-06-26 16:58:36 -06001795}
1796
1797bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1798{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001799 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001800
qining40887662016-04-03 22:20:42 -04001801 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1802 if (node->getType().getQualifier().isSpecConstant())
1803 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1804
John Kessenichfc51d282015-08-19 13:34:18 -06001805 spv::Id result = spv::NoResult;
1806
1807 // try texturing first
1808 result = createImageTextureFunctionCall(node);
1809 if (result != spv::NoResult) {
1810 builder.clearAccessChain();
1811 builder.setAccessChainRValue(result);
1812
1813 return false; // done with this node
1814 }
1815
1816 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001817
1818 if (node->getOp() == glslang::EOpArrayLength) {
1819 // Quite special; won't want to evaluate the operand.
1820
John Kessenich5611c6d2018-04-05 11:25:02 -06001821 // Currently, the front-end does not allow .length() on an array until it is sized,
1822 // except for the last block membeor of an SSBO.
1823 // TODO: If this changes, link-time sized arrays might show up here, and need their
1824 // size extracted.
1825
John Kessenichc9a80832015-09-12 12:17:44 -06001826 // Normal .length() would have been constant folded by the front-end.
1827 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001828 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001829
John Kessenichc9a80832015-09-12 12:17:44 -06001830 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1831 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001832 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1833 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001834
John Kessenich8c869672018-11-28 07:01:37 -07001835 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1836 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1837 // AST expectation of a signed result.
1838 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl)
1839 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1840
John Kessenichc9a80832015-09-12 12:17:44 -06001841 builder.clearAccessChain();
1842 builder.setAccessChainRValue(length);
1843
1844 return false;
1845 }
1846
John Kessenichfc51d282015-08-19 13:34:18 -06001847 // Start by evaluating the operand
1848
John Kessenich8c8505c2016-07-26 12:50:38 -06001849 // Does it need a swizzle inversion? If so, evaluation is inverted;
1850 // operate first on the swizzle base, then apply the swizzle.
1851 spv::Id invertedType = spv::NoType;
1852 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1853 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1854 invertedType = getInvertedSwizzleType(*node->getOperand());
1855
John Kessenich140f3df2015-06-26 16:58:36 -06001856 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001857 if (invertedType != spv::NoType)
1858 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1859 else
1860 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001861
Rex Xufc618912015-09-09 16:42:49 +08001862 spv::Id operand = spv::NoResult;
1863
1864 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1865 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001866 node->getOp() == glslang::EOpAtomicCounter ||
1867 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001868 operand = builder.accessChainGetLValue(); // Special case l-value operands
1869 else
John Kessenich32cfd492016-02-02 12:37:46 -07001870 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001871
John Kessenichead86222018-03-28 18:01:20 -06001872 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001873 TranslateNoContractionDecoration(node->getType().getQualifier()),
1874 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001875
1876 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001877 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001878 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001879
1880 // if not, then possibly an operation
1881 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001882 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001883
1884 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001885 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001886 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001887 builder.addDecoration(result, decorations.nonUniform);
1888 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001889
John Kessenich140f3df2015-06-26 16:58:36 -06001890 builder.clearAccessChain();
1891 builder.setAccessChainRValue(result);
1892
1893 return false; // done with this node
1894 }
1895
1896 // it must be a special case, check...
1897 switch (node->getOp()) {
1898 case glslang::EOpPostIncrement:
1899 case glslang::EOpPostDecrement:
1900 case glslang::EOpPreIncrement:
1901 case glslang::EOpPreDecrement:
1902 {
1903 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001904 spv::Id one = 0;
1905 if (node->getBasicType() == glslang::EbtFloat)
1906 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001907 else if (node->getBasicType() == glslang::EbtDouble)
1908 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001909 else if (node->getBasicType() == glslang::EbtFloat16)
1910 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001911 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1912 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001913 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1914 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001915 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1916 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001917 else
1918 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 glslang::TOperator op;
1920 if (node->getOp() == glslang::EOpPreIncrement ||
1921 node->getOp() == glslang::EOpPostIncrement)
1922 op = glslang::EOpAdd;
1923 else
1924 op = glslang::EOpSub;
1925
John Kessenichead86222018-03-28 18:01:20 -06001926 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001927 convertGlslangToSpvType(node->getType()), operand, one,
1928 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001929 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001930
1931 // The result of operation is always stored, but conditionally the
1932 // consumed result. The consumed result is always an r-value.
1933 builder.accessChainStore(result);
1934 builder.clearAccessChain();
1935 if (node->getOp() == glslang::EOpPreIncrement ||
1936 node->getOp() == glslang::EOpPreDecrement)
1937 builder.setAccessChainRValue(result);
1938 else
1939 builder.setAccessChainRValue(operand);
1940 }
1941
1942 return false;
1943
1944 case glslang::EOpEmitStreamVertex:
1945 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1946 return false;
1947 case glslang::EOpEndStreamPrimitive:
1948 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1949 return false;
1950
1951 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001952 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001953 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001954 }
John Kessenich140f3df2015-06-26 16:58:36 -06001955}
1956
1957bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1958{
qining27e04a02016-04-14 16:40:20 -04001959 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1960 if (node->getType().getQualifier().isSpecConstant())
1961 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1962
John Kessenichfc51d282015-08-19 13:34:18 -06001963 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001964 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1965 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001966
1967 // try texturing
1968 result = createImageTextureFunctionCall(node);
1969 if (result != spv::NoResult) {
1970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(result);
1972
1973 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001974 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001975#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001976 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001977#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001978 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001979 // "imageStore" is a special case, which has no result
1980 return false;
1981 }
John Kessenichfc51d282015-08-19 13:34:18 -06001982
John Kessenich140f3df2015-06-26 16:58:36 -06001983 glslang::TOperator binOp = glslang::EOpNull;
1984 bool reduceComparison = true;
1985 bool isMatrix = false;
1986 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001987 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001988
1989 assert(node->getOp());
1990
John Kessenichf6640762016-08-01 19:44:00 -06001991 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001992
1993 switch (node->getOp()) {
1994 case glslang::EOpSequence:
1995 {
1996 if (preVisit)
1997 ++sequenceDepth;
1998 else
1999 --sequenceDepth;
2000
2001 if (sequenceDepth == 1) {
2002 // If this is the parent node of all the functions, we want to see them
2003 // early, so all call points have actual SPIR-V functions to reference.
2004 // In all cases, still let the traverser visit the children for us.
2005 makeFunctions(node->getAsAggregate()->getSequence());
2006
John Kessenich6fccb3c2016-09-19 16:01:41 -06002007 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002008 // anything else gets there, so visit out of order, doing them all now.
2009 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2010
John Kessenich6a60c2f2016-12-08 21:01:59 -07002011 // 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 -06002012 // so do them manually.
2013 visitFunctions(node->getAsAggregate()->getSequence());
2014
2015 return false;
2016 }
2017
2018 return true;
2019 }
2020 case glslang::EOpLinkerObjects:
2021 {
2022 if (visit == glslang::EvPreVisit)
2023 linkageOnly = true;
2024 else
2025 linkageOnly = false;
2026
2027 return true;
2028 }
2029 case glslang::EOpComma:
2030 {
2031 // processing from left to right naturally leaves the right-most
2032 // lying around in the access chain
2033 glslang::TIntermSequence& glslangOperands = node->getSequence();
2034 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2035 glslangOperands[i]->traverse(this);
2036
2037 return false;
2038 }
2039 case glslang::EOpFunction:
2040 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002041 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002042 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002043 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002044 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002045 } else {
2046 handleFunctionEntry(node);
2047 }
2048 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002049 if (inEntryPoint)
2050 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002051 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002052 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
2054
2055 return true;
2056 case glslang::EOpParameters:
2057 // Parameters will have been consumed by EOpFunction processing, but not
2058 // the body, so we still visited the function node's children, making this
2059 // child redundant.
2060 return false;
2061 case glslang::EOpFunctionCall:
2062 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002063 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002064 if (node->isUserDefined())
2065 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002066 // 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 -07002067 if (result) {
2068 builder.clearAccessChain();
2069 builder.setAccessChainRValue(result);
2070 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002071 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002072
2073 return false;
2074 }
2075 case glslang::EOpConstructMat2x2:
2076 case glslang::EOpConstructMat2x3:
2077 case glslang::EOpConstructMat2x4:
2078 case glslang::EOpConstructMat3x2:
2079 case glslang::EOpConstructMat3x3:
2080 case glslang::EOpConstructMat3x4:
2081 case glslang::EOpConstructMat4x2:
2082 case glslang::EOpConstructMat4x3:
2083 case glslang::EOpConstructMat4x4:
2084 case glslang::EOpConstructDMat2x2:
2085 case glslang::EOpConstructDMat2x3:
2086 case glslang::EOpConstructDMat2x4:
2087 case glslang::EOpConstructDMat3x2:
2088 case glslang::EOpConstructDMat3x3:
2089 case glslang::EOpConstructDMat3x4:
2090 case glslang::EOpConstructDMat4x2:
2091 case glslang::EOpConstructDMat4x3:
2092 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002093 case glslang::EOpConstructIMat2x2:
2094 case glslang::EOpConstructIMat2x3:
2095 case glslang::EOpConstructIMat2x4:
2096 case glslang::EOpConstructIMat3x2:
2097 case glslang::EOpConstructIMat3x3:
2098 case glslang::EOpConstructIMat3x4:
2099 case glslang::EOpConstructIMat4x2:
2100 case glslang::EOpConstructIMat4x3:
2101 case glslang::EOpConstructIMat4x4:
2102 case glslang::EOpConstructUMat2x2:
2103 case glslang::EOpConstructUMat2x3:
2104 case glslang::EOpConstructUMat2x4:
2105 case glslang::EOpConstructUMat3x2:
2106 case glslang::EOpConstructUMat3x3:
2107 case glslang::EOpConstructUMat3x4:
2108 case glslang::EOpConstructUMat4x2:
2109 case glslang::EOpConstructUMat4x3:
2110 case glslang::EOpConstructUMat4x4:
2111 case glslang::EOpConstructBMat2x2:
2112 case glslang::EOpConstructBMat2x3:
2113 case glslang::EOpConstructBMat2x4:
2114 case glslang::EOpConstructBMat3x2:
2115 case glslang::EOpConstructBMat3x3:
2116 case glslang::EOpConstructBMat3x4:
2117 case glslang::EOpConstructBMat4x2:
2118 case glslang::EOpConstructBMat4x3:
2119 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002120 case glslang::EOpConstructF16Mat2x2:
2121 case glslang::EOpConstructF16Mat2x3:
2122 case glslang::EOpConstructF16Mat2x4:
2123 case glslang::EOpConstructF16Mat3x2:
2124 case glslang::EOpConstructF16Mat3x3:
2125 case glslang::EOpConstructF16Mat3x4:
2126 case glslang::EOpConstructF16Mat4x2:
2127 case glslang::EOpConstructF16Mat4x3:
2128 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002129 isMatrix = true;
2130 // fall through
2131 case glslang::EOpConstructFloat:
2132 case glslang::EOpConstructVec2:
2133 case glslang::EOpConstructVec3:
2134 case glslang::EOpConstructVec4:
2135 case glslang::EOpConstructDouble:
2136 case glslang::EOpConstructDVec2:
2137 case glslang::EOpConstructDVec3:
2138 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002139 case glslang::EOpConstructFloat16:
2140 case glslang::EOpConstructF16Vec2:
2141 case glslang::EOpConstructF16Vec3:
2142 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002143 case glslang::EOpConstructBool:
2144 case glslang::EOpConstructBVec2:
2145 case glslang::EOpConstructBVec3:
2146 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002147 case glslang::EOpConstructInt8:
2148 case glslang::EOpConstructI8Vec2:
2149 case glslang::EOpConstructI8Vec3:
2150 case glslang::EOpConstructI8Vec4:
2151 case glslang::EOpConstructUint8:
2152 case glslang::EOpConstructU8Vec2:
2153 case glslang::EOpConstructU8Vec3:
2154 case glslang::EOpConstructU8Vec4:
2155 case glslang::EOpConstructInt16:
2156 case glslang::EOpConstructI16Vec2:
2157 case glslang::EOpConstructI16Vec3:
2158 case glslang::EOpConstructI16Vec4:
2159 case glslang::EOpConstructUint16:
2160 case glslang::EOpConstructU16Vec2:
2161 case glslang::EOpConstructU16Vec3:
2162 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002163 case glslang::EOpConstructInt:
2164 case glslang::EOpConstructIVec2:
2165 case glslang::EOpConstructIVec3:
2166 case glslang::EOpConstructIVec4:
2167 case glslang::EOpConstructUint:
2168 case glslang::EOpConstructUVec2:
2169 case glslang::EOpConstructUVec3:
2170 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002171 case glslang::EOpConstructInt64:
2172 case glslang::EOpConstructI64Vec2:
2173 case glslang::EOpConstructI64Vec3:
2174 case glslang::EOpConstructI64Vec4:
2175 case glslang::EOpConstructUint64:
2176 case glslang::EOpConstructU64Vec2:
2177 case glslang::EOpConstructU64Vec3:
2178 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002179 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002180 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002181 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002182 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002183 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002184 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002185 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002186 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002188 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002189 std::vector<spv::Id> constituents;
2190 for (int c = 0; c < (int)arguments.size(); ++c)
2191 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002192 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002193 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002194 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002195 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002196 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002197
2198 builder.clearAccessChain();
2199 builder.setAccessChainRValue(constructed);
2200
2201 return false;
2202 }
2203
2204 // These six are component-wise compares with component-wise results.
2205 // Forward on to createBinaryOperation(), requesting a vector result.
2206 case glslang::EOpLessThan:
2207 case glslang::EOpGreaterThan:
2208 case glslang::EOpLessThanEqual:
2209 case glslang::EOpGreaterThanEqual:
2210 case glslang::EOpVectorEqual:
2211 case glslang::EOpVectorNotEqual:
2212 {
2213 // Map the operation to a binary
2214 binOp = node->getOp();
2215 reduceComparison = false;
2216 switch (node->getOp()) {
2217 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2218 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2219 default: binOp = node->getOp(); break;
2220 }
2221
2222 break;
2223 }
2224 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002225 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002226 binOp = glslang::EOpMul;
2227 break;
2228 case glslang::EOpOuterProduct:
2229 // two vectors multiplied to make a matrix
2230 binOp = glslang::EOpOuterProduct;
2231 break;
2232 case glslang::EOpDot:
2233 {
qining25262b32016-05-06 17:25:16 -04002234 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002235 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002236 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002237 binOp = glslang::EOpMul;
2238 break;
2239 }
2240 case glslang::EOpMod:
2241 // when an aggregate, this is the floating-point mod built-in function,
2242 // which can be emitted by the one in createBinaryOperation()
2243 binOp = glslang::EOpMod;
2244 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002245 case glslang::EOpEmitVertex:
2246 case glslang::EOpEndPrimitive:
2247 case glslang::EOpBarrier:
2248 case glslang::EOpMemoryBarrier:
2249 case glslang::EOpMemoryBarrierAtomicCounter:
2250 case glslang::EOpMemoryBarrierBuffer:
2251 case glslang::EOpMemoryBarrierImage:
2252 case glslang::EOpMemoryBarrierShared:
2253 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002254 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002255 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002256 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002257 case glslang::EOpWorkgroupMemoryBarrier:
2258 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002259 case glslang::EOpSubgroupBarrier:
2260 case glslang::EOpSubgroupMemoryBarrier:
2261 case glslang::EOpSubgroupMemoryBarrierBuffer:
2262 case glslang::EOpSubgroupMemoryBarrierImage:
2263 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002264 noReturnValue = true;
2265 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2266 break;
2267
Jeff Bolz36831c92018-09-05 10:11:41 -05002268 case glslang::EOpAtomicStore:
2269 noReturnValue = true;
2270 // fallthrough
2271 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002272 case glslang::EOpAtomicAdd:
2273 case glslang::EOpAtomicMin:
2274 case glslang::EOpAtomicMax:
2275 case glslang::EOpAtomicAnd:
2276 case glslang::EOpAtomicOr:
2277 case glslang::EOpAtomicXor:
2278 case glslang::EOpAtomicExchange:
2279 case glslang::EOpAtomicCompSwap:
2280 atomic = true;
2281 break;
2282
John Kessenich0d0c6d32017-07-23 16:08:26 -06002283 case glslang::EOpAtomicCounterAdd:
2284 case glslang::EOpAtomicCounterSubtract:
2285 case glslang::EOpAtomicCounterMin:
2286 case glslang::EOpAtomicCounterMax:
2287 case glslang::EOpAtomicCounterAnd:
2288 case glslang::EOpAtomicCounterOr:
2289 case glslang::EOpAtomicCounterXor:
2290 case glslang::EOpAtomicCounterExchange:
2291 case glslang::EOpAtomicCounterCompSwap:
2292 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2293 builder.addCapability(spv::CapabilityAtomicStorageOps);
2294 atomic = true;
2295 break;
2296
Chao Chen3c366992018-09-19 11:41:59 -07002297#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002298 case glslang::EOpIgnoreIntersectionNV:
2299 case glslang::EOpTerminateRayNV:
2300 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002301 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002302 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2303 noReturnValue = true;
2304 break;
2305#endif
2306
John Kessenich140f3df2015-06-26 16:58:36 -06002307 default:
2308 break;
2309 }
2310
2311 //
2312 // See if it maps to a regular operation.
2313 //
John Kessenich140f3df2015-06-26 16:58:36 -06002314 if (binOp != glslang::EOpNull) {
2315 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2316 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2317 assert(left && right);
2318
2319 builder.clearAccessChain();
2320 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002321 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002322
2323 builder.clearAccessChain();
2324 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002325 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002326
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002327 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002328 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002329 TranslateNoContractionDecoration(node->getType().getQualifier()),
2330 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002331 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002332 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002333 left->getType().getBasicType(), reduceComparison);
2334
2335 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002336 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002337 builder.clearAccessChain();
2338 builder.setAccessChainRValue(result);
2339
2340 return false;
2341 }
2342
John Kessenich426394d2015-07-23 10:22:48 -06002343 //
2344 // Create the list of operands.
2345 //
John Kessenich140f3df2015-06-26 16:58:36 -06002346 glslang::TIntermSequence& glslangOperands = node->getSequence();
2347 std::vector<spv::Id> operands;
2348 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002349 // special case l-value operands; there are just a few
2350 bool lvalue = false;
2351 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002352 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002353 case glslang::EOpModf:
2354 if (arg == 1)
2355 lvalue = true;
2356 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002357 case glslang::EOpInterpolateAtSample:
2358 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002359#ifdef AMD_EXTENSIONS
2360 case glslang::EOpInterpolateAtVertex:
2361#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002362 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002363 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002364
2365 // Does it need a swizzle inversion? If so, evaluation is inverted;
2366 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002367 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002368 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2369 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2370 }
Rex Xu7a26c172015-12-08 17:12:09 +08002371 break;
Rex Xud4782c12015-09-06 16:30:11 +08002372 case glslang::EOpAtomicAdd:
2373 case glslang::EOpAtomicMin:
2374 case glslang::EOpAtomicMax:
2375 case glslang::EOpAtomicAnd:
2376 case glslang::EOpAtomicOr:
2377 case glslang::EOpAtomicXor:
2378 case glslang::EOpAtomicExchange:
2379 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002380 case glslang::EOpAtomicLoad:
2381 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002382 case glslang::EOpAtomicCounterAdd:
2383 case glslang::EOpAtomicCounterSubtract:
2384 case glslang::EOpAtomicCounterMin:
2385 case glslang::EOpAtomicCounterMax:
2386 case glslang::EOpAtomicCounterAnd:
2387 case glslang::EOpAtomicCounterOr:
2388 case glslang::EOpAtomicCounterXor:
2389 case glslang::EOpAtomicCounterExchange:
2390 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002391 if (arg == 0)
2392 lvalue = true;
2393 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002394 case glslang::EOpAddCarry:
2395 case glslang::EOpSubBorrow:
2396 if (arg == 2)
2397 lvalue = true;
2398 break;
2399 case glslang::EOpUMulExtended:
2400 case glslang::EOpIMulExtended:
2401 if (arg >= 2)
2402 lvalue = true;
2403 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002404 default:
2405 break;
2406 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002407 builder.clearAccessChain();
2408 if (invertedType != spv::NoType && arg == 0)
2409 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2410 else
2411 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002412 if (lvalue)
2413 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002414 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002415 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002416 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002417 }
John Kessenich140f3df2015-06-26 16:58:36 -06002418 }
John Kessenich426394d2015-07-23 10:22:48 -06002419
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002420 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich426394d2015-07-23 10:22:48 -06002421 if (atomic) {
2422 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002423 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002424 } else {
2425 // Pass through to generic operations.
2426 switch (glslangOperands.size()) {
2427 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002428 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002429 break;
2430 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002431 {
2432 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002433 TranslateNoContractionDecoration(node->getType().getQualifier()),
2434 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002435 result = createUnaryOperation(
2436 node->getOp(), decorations,
2437 resultType(), operands.front(),
2438 glslangOperands[0]->getAsTyped()->getBasicType());
2439 }
John Kessenich426394d2015-07-23 10:22:48 -06002440 break;
2441 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002442 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002443 break;
2444 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002445 if (invertedType)
2446 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002447 }
2448
2449 if (noReturnValue)
2450 return false;
2451
2452 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002453 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002454 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002455 } else {
2456 builder.clearAccessChain();
2457 builder.setAccessChainRValue(result);
2458 return false;
2459 }
2460}
2461
John Kessenich433e9ff2017-01-26 20:31:11 -07002462// This path handles both if-then-else and ?:
2463// The if-then-else has a node type of void, while
2464// ?: has either a void or a non-void node type
2465//
2466// Leaving the result, when not void:
2467// GLSL only has r-values as the result of a :?, but
2468// if we have an l-value, that can be more efficient if it will
2469// become the base of a complex r-value expression, because the
2470// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002471bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2472{
John Kessenich4bee5312018-02-20 21:29:05 -07002473 // See if it simple and safe, or required, to execute both sides.
2474 // Crucially, side effects must be either semantically required or avoided,
2475 // and there are performance trade-offs.
2476 // Return true if required or a good idea (and safe) to execute both sides,
2477 // false otherwise.
2478 const auto bothSidesPolicy = [&]() -> bool {
2479 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002480 if (node->getTrueBlock() == nullptr ||
2481 node->getFalseBlock() == nullptr)
2482 return false;
2483
John Kessenich4bee5312018-02-20 21:29:05 -07002484 // required? (unless we write additional code to look for side effects
2485 // and make performance trade-offs if none are present)
2486 if (!node->getShortCircuit())
2487 return true;
2488
2489 // if not required to execute both, decide based on performance/practicality...
2490
2491 // see if OpSelect can handle it
2492 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2493 node->getBasicType() == glslang::EbtVoid)
2494 return false;
2495
John Kessenich433e9ff2017-01-26 20:31:11 -07002496 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2497 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2498
2499 // return true if a single operand to ? : is okay for OpSelect
2500 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002501 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002502 };
2503
2504 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2505 operandOkay(node->getFalseBlock()->getAsTyped());
2506 };
2507
John Kessenich4bee5312018-02-20 21:29:05 -07002508 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2509 // emit the condition before doing anything with selection
2510 node->getCondition()->traverse(this);
2511 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2512
2513 // Find a way of executing both sides and selecting the right result.
2514 const auto executeBothSides = [&]() -> void {
2515 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002516 node->getTrueBlock()->traverse(this);
2517 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2518 node->getFalseBlock()->traverse(this);
2519 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2520
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002521 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002522
John Kessenich4bee5312018-02-20 21:29:05 -07002523 // done if void
2524 if (node->getBasicType() == glslang::EbtVoid)
2525 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002526
John Kessenich4bee5312018-02-20 21:29:05 -07002527 // emit code to select between trueValue and falseValue
2528
2529 // see if OpSelect can handle it
2530 if (node->getType().isScalar() || node->getType().isVector()) {
2531 // Emit OpSelect for this selection.
2532
2533 // smear condition to vector, if necessary (AST is always scalar)
2534 if (builder.isVector(trueValue))
2535 condition = builder.smearScalar(spv::NoPrecision, condition,
2536 builder.makeVectorType(builder.makeBoolType(),
2537 builder.getNumComponents(trueValue)));
2538
2539 // OpSelect
2540 result = builder.createTriOp(spv::OpSelect,
2541 convertGlslangToSpvType(node->getType()), condition,
2542 trueValue, falseValue);
2543
2544 builder.clearAccessChain();
2545 builder.setAccessChainRValue(result);
2546 } else {
2547 // We need control flow to select the result.
2548 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2549 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2550
2551 // Selection control:
2552 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2553
2554 // make an "if" based on the value created by the condition
2555 spv::Builder::If ifBuilder(condition, control, builder);
2556
2557 // emit the "then" statement
2558 builder.createStore(trueValue, result);
2559 ifBuilder.makeBeginElse();
2560 // emit the "else" statement
2561 builder.createStore(falseValue, result);
2562
2563 // finish off the control flow
2564 ifBuilder.makeEndIf();
2565
2566 builder.clearAccessChain();
2567 builder.setAccessChainLValue(result);
2568 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002569 };
2570
John Kessenich4bee5312018-02-20 21:29:05 -07002571 // Execute the one side needed, as per the condition
2572 const auto executeOneSide = [&]() {
2573 // Always emit control flow.
2574 if (node->getBasicType() != glslang::EbtVoid)
2575 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002576
John Kessenich4bee5312018-02-20 21:29:05 -07002577 // Selection control:
2578 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2579
2580 // make an "if" based on the value created by the condition
2581 spv::Builder::If ifBuilder(condition, control, builder);
2582
2583 // emit the "then" statement
2584 if (node->getTrueBlock() != nullptr) {
2585 node->getTrueBlock()->traverse(this);
2586 if (result != spv::NoResult)
2587 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2588 }
2589
2590 if (node->getFalseBlock() != nullptr) {
2591 ifBuilder.makeBeginElse();
2592 // emit the "else" statement
2593 node->getFalseBlock()->traverse(this);
2594 if (result != spv::NoResult)
2595 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2596 }
2597
2598 // finish off the control flow
2599 ifBuilder.makeEndIf();
2600
2601 if (result != spv::NoResult) {
2602 builder.clearAccessChain();
2603 builder.setAccessChainLValue(result);
2604 }
2605 };
2606
2607 // Try for OpSelect (or a requirement to execute both sides)
2608 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002609 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2610 if (node->getType().getQualifier().isSpecConstant())
2611 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002612 executeBothSides();
2613 } else
2614 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002615
2616 return false;
2617}
2618
2619bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2620{
2621 // emit and get the condition before doing anything with switch
2622 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002623 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002624
Rex Xu57e65922017-07-04 23:23:40 +08002625 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002626 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002627
John Kessenich140f3df2015-06-26 16:58:36 -06002628 // browse the children to sort out code segments
2629 int defaultSegment = -1;
2630 std::vector<TIntermNode*> codeSegments;
2631 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2632 std::vector<int> caseValues;
2633 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2634 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2635 TIntermNode* child = *c;
2636 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002637 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002638 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002639 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002640 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2641 } else
2642 codeSegments.push_back(child);
2643 }
2644
qining25262b32016-05-06 17:25:16 -04002645 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002646 // statements between the last case and the end of the switch statement
2647 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2648 (int)codeSegments.size() == defaultSegment)
2649 codeSegments.push_back(nullptr);
2650
2651 // make the switch statement
2652 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002653 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002654
2655 // emit all the code in the segments
2656 breakForLoop.push(false);
2657 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2658 builder.nextSwitchSegment(segmentBlocks, s);
2659 if (codeSegments[s])
2660 codeSegments[s]->traverse(this);
2661 else
2662 builder.addSwitchBreak();
2663 }
2664 breakForLoop.pop();
2665
2666 builder.endSwitch(segmentBlocks);
2667
2668 return false;
2669}
2670
2671void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2672{
2673 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002674 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002675
2676 builder.clearAccessChain();
2677 builder.setAccessChainRValue(constant);
2678}
2679
2680bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2681{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002682 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002683 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002684
2685 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002686 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2687 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002688
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002689 // Spec requires back edges to target header blocks, and every header block
2690 // must dominate its merge block. Make a header block first to ensure these
2691 // conditions are met. By definition, it will contain OpLoopMerge, followed
2692 // by a block-ending branch. But we don't want to put any other body/test
2693 // instructions in it, since the body/test may have arbitrary instructions,
2694 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002695 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002696 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002697 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002698 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002699 spv::Block& test = builder.makeNewBlock();
2700 builder.createBranch(&test);
2701
2702 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002703 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002704 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002705 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2706
2707 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002708 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002709 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002710 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002711 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002712 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002713
2714 builder.setBuildPoint(&blocks.continue_target);
2715 if (node->getTerminal())
2716 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002717 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002718 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002719 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002720 builder.createBranch(&blocks.body);
2721
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002722 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002723 builder.setBuildPoint(&blocks.body);
2724 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002725 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002726 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002727 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002728
2729 builder.setBuildPoint(&blocks.continue_target);
2730 if (node->getTerminal())
2731 node->getTerminal()->traverse(this);
2732 if (node->getTest()) {
2733 node->getTest()->traverse(this);
2734 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002735 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002736 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002737 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002738 // TODO: unless there was a break/return/discard instruction
2739 // somewhere in the body, this is an infinite loop, so we should
2740 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002741 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002742 }
John Kessenich140f3df2015-06-26 16:58:36 -06002743 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002744 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002745 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002746 return false;
2747}
2748
2749bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2750{
2751 if (node->getExpression())
2752 node->getExpression()->traverse(this);
2753
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002754 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002755
John Kessenich140f3df2015-06-26 16:58:36 -06002756 switch (node->getFlowOp()) {
2757 case glslang::EOpKill:
2758 builder.makeDiscard();
2759 break;
2760 case glslang::EOpBreak:
2761 if (breakForLoop.top())
2762 builder.createLoopExit();
2763 else
2764 builder.addSwitchBreak();
2765 break;
2766 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002767 builder.createLoopContinue();
2768 break;
2769 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002770 if (node->getExpression()) {
2771 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2772 spv::Id returnId = accessChainLoad(glslangReturnType);
2773 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2774 builder.clearAccessChain();
2775 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2776 builder.setAccessChainLValue(copyId);
2777 multiTypeStore(glslangReturnType, returnId);
2778 returnId = builder.createLoad(copyId);
2779 }
2780 builder.makeReturn(false, returnId);
2781 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002782 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002783
2784 builder.clearAccessChain();
2785 break;
2786
2787 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002788 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002789 break;
2790 }
2791
2792 return false;
2793}
2794
2795spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2796{
qining25262b32016-05-06 17:25:16 -04002797 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002798 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002799 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002800 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002801 spv::Id result = createSpvConstant(*node);
2802 if (result != spv::NoResult)
2803 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002804 }
2805
2806 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002807 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002808 spv::Id spvType = convertGlslangToSpvType(node->getType());
2809
Rex Xucabbb782017-03-24 13:41:14 +08002810 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2811 node->getType().containsBasicType(glslang::EbtInt16) ||
2812 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002813 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002814 switch (storageClass) {
2815 case spv::StorageClassInput:
2816 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002817 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002818 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002819 break;
2820 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002821 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002822 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002823 break;
2824 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002825 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002826 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2827 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002828 else
2829 builder.addCapability(spv::CapabilityStorageUniform16);
2830 break;
2831 case spv::StorageClassStorageBuffer:
2832 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2833 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2834 break;
2835 default:
2836 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002837 }
2838 }
Rex Xuf89ad982017-04-07 23:22:33 +08002839
John Kessenich312dcfb2018-07-03 13:19:51 -06002840 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2841 node->getType().containsBasicType(glslang::EbtUint8);
2842 if (contains8BitType) {
2843 if (storageClass == spv::StorageClassPushConstant) {
2844 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2845 builder.addCapability(spv::CapabilityStoragePushConstant8);
2846 } else if (storageClass == spv::StorageClassUniform) {
2847 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2848 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002849 } else if (storageClass == spv::StorageClassStorageBuffer) {
2850 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2851 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002852 }
2853 }
2854
John Kessenich140f3df2015-06-26 16:58:36 -06002855 const char* name = node->getName().c_str();
2856 if (glslang::IsAnonymous(name))
2857 name = "";
2858
2859 return builder.createVariable(storageClass, spvType, name);
2860}
2861
2862// Return type Id of the sampled type.
2863spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2864{
2865 switch (sampler.type) {
2866 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002867#ifdef AMD_EXTENSIONS
2868 case glslang::EbtFloat16:
2869 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2870 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2871 return builder.makeFloatType(16);
2872#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002873 case glslang::EbtInt: return builder.makeIntType(32);
2874 case glslang::EbtUint: return builder.makeUintType(32);
2875 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002876 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002877 return builder.makeFloatType(32);
2878 }
2879}
2880
John Kessenich8c8505c2016-07-26 12:50:38 -06002881// If node is a swizzle operation, return the type that should be used if
2882// the swizzle base is first consumed by another operation, before the swizzle
2883// is applied.
2884spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2885{
John Kessenichecba76f2017-01-06 00:34:48 -07002886 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002887 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2888 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2889 else
2890 return spv::NoType;
2891}
2892
2893// When inverting a swizzle with a parent op, this function
2894// will apply the swizzle operation to a completed parent operation.
2895spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2896{
2897 std::vector<unsigned> swizzle;
2898 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2899 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2900}
2901
John Kessenich8c8505c2016-07-26 12:50:38 -06002902// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2903void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2904{
2905 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2906 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2907 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2908}
2909
John Kessenich3ac051e2015-12-20 11:29:16 -07002910// Convert from a glslang type to an SPV type, by calling into a
2911// recursive version of this function. This establishes the inherited
2912// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002913spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2914{
John Kessenichead86222018-03-28 18:01:20 -06002915 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002916}
2917
2918// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002919// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002920// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002921spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2922 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002923{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002924 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002925
2926 switch (type.getBasicType()) {
2927 case glslang::EbtVoid:
2928 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002929 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002930 break;
2931 case glslang::EbtFloat:
2932 spvType = builder.makeFloatType(32);
2933 break;
2934 case glslang::EbtDouble:
2935 spvType = builder.makeFloatType(64);
2936 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002937 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002938 spvType = builder.makeFloatType(16);
2939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002941 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2942 // a 32-bit int where non-0 means true.
2943 if (explicitLayout != glslang::ElpNone)
2944 spvType = builder.makeUintType(32);
2945 else
2946 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002947 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002948 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002949 spvType = builder.makeIntType(8);
2950 break;
2951 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002952 spvType = builder.makeUintType(8);
2953 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002954 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002955 spvType = builder.makeIntType(16);
2956 break;
2957 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002958 spvType = builder.makeUintType(16);
2959 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 case glslang::EbtInt:
2961 spvType = builder.makeIntType(32);
2962 break;
2963 case glslang::EbtUint:
2964 spvType = builder.makeUintType(32);
2965 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002966 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002967 spvType = builder.makeIntType(64);
2968 break;
2969 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002970 spvType = builder.makeUintType(64);
2971 break;
John Kessenich426394d2015-07-23 10:22:48 -06002972 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002973 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002974 spvType = builder.makeUintType(32);
2975 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002976#ifdef NV_EXTENSIONS
2977 case glslang::EbtAccStructNV:
2978 spvType = builder.makeAccelerationStructureNVType();
2979 break;
2980#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002981 case glslang::EbtSampler:
2982 {
2983 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002984 if (sampler.sampler) {
2985 // pure sampler
2986 spvType = builder.makeSamplerType();
2987 } else {
2988 // an image is present, make its type
2989 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2990 sampler.image ? 2 : 1, TranslateImageFormat(type));
2991 if (sampler.combined) {
2992 // already has both image and sampler, make the combined type
2993 spvType = builder.makeSampledImageType(spvType);
2994 }
John Kessenich55e7d112015-11-15 21:33:39 -07002995 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002996 }
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998 case glslang::EbtStruct:
2999 case glslang::EbtBlock:
3000 {
3001 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003002 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003003
3004 // Try to share structs for different layouts, but not yet for other
3005 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003006 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003007 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003008 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003009 break;
3010
3011 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003012 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003013 memberRemapper[glslangMembers].resize(glslangMembers->size());
3014 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003015 }
3016 break;
3017 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003018 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020 }
3021
3022 if (type.isMatrix())
3023 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3024 else {
3025 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3026 if (type.getVectorSize() > 1)
3027 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3028 }
3029
3030 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003031 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3032
John Kessenichc9a80832015-09-12 12:17:44 -06003033 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003034 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003035 // We need to decorate array strides for types needing explicit layout, except blocks.
3036 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003037 // Use a dummy glslang type for querying internal strides of
3038 // arrays of arrays, but using just a one-dimensional array.
3039 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003040 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3041 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003042
3043 // Will compute the higher-order strides here, rather than making a whole
3044 // pile of types and doing repetitive recursion on their contents.
3045 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3046 }
John Kessenichf8842e52016-01-04 19:22:56 -07003047
3048 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003049 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003050 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003051 if (stride > 0)
3052 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003053 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003054 }
3055 } else {
3056 // single-dimensional array, and don't yet have stride
3057
John Kessenichf8842e52016-01-04 19:22:56 -07003058 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003059 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3060 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003061 }
John Kessenich31ed4832015-09-09 17:51:38 -06003062
John Kessenichead86222018-03-28 18:01:20 -06003063 // Do the outer dimension, which might not be known for a runtime-sized array.
3064 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3065 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003066 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003067 else {
3068 if (!lastBufferBlockMember) {
3069 builder.addExtension("SPV_EXT_descriptor_indexing");
3070 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3071 }
John Kessenichead86222018-03-28 18:01:20 -06003072 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003073 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003074 if (stride > 0)
3075 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003076 }
3077
3078 return spvType;
3079}
3080
John Kessenich0e737842017-03-24 18:38:16 -06003081// TODO: this functionality should exist at a higher level, in creating the AST
3082//
3083// Identify interface members that don't have their required extension turned on.
3084//
3085bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3086{
Chao Chen3c366992018-09-19 11:41:59 -07003087#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003088 auto& extensions = glslangIntermediate->getRequestedExtensions();
3089
Rex Xubcf291a2017-03-29 23:01:36 +08003090 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3091 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3092 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003093 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3094 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3095 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003096
3097 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3098 if (member.getFieldName() == "gl_ViewportMask" &&
3099 extensions.find("GL_NV_viewport_array2") == extensions.end())
3100 return true;
3101 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3102 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3103 return true;
3104 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3105 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3106 return true;
3107 }
3108#endif
John Kessenich0e737842017-03-24 18:38:16 -06003109
3110 return false;
3111};
3112
John Kessenich6090df02016-06-30 21:18:02 -06003113// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3114// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3115// Mutually recursive with convertGlslangToSpvType().
3116spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3117 const glslang::TTypeList* glslangMembers,
3118 glslang::TLayoutPacking explicitLayout,
3119 const glslang::TQualifier& qualifier)
3120{
3121 // Create a vector of struct types for SPIR-V to consume
3122 std::vector<spv::Id> spvMembers;
3123 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 -06003124 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3125 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3126 if (glslangMember.hiddenMember()) {
3127 ++memberDelta;
3128 if (type.getBasicType() == glslang::EbtBlock)
3129 memberRemapper[glslangMembers][i] = -1;
3130 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003131 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003132 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003133 if (filterMember(glslangMember))
3134 continue;
3135 }
John Kessenich6090df02016-06-30 21:18:02 -06003136 // modify just this child's view of the qualifier
3137 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3138 InheritQualifiers(memberQualifier, qualifier);
3139
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003140 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003141 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003142 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003143
3144 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003145 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3146 i == (int)glslangMembers->size() - 1;
3147 spvMembers.push_back(
3148 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003149 }
3150 }
3151
3152 // Make the SPIR-V type
3153 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003154 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003155 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3156
3157 // Decorate it
3158 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3159
3160 return spvType;
3161}
3162
3163void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3164 const glslang::TTypeList* glslangMembers,
3165 glslang::TLayoutPacking explicitLayout,
3166 const glslang::TQualifier& qualifier,
3167 spv::Id spvType)
3168{
3169 // Name and decorate the non-hidden members
3170 int offset = -1;
3171 int locationOffset = 0; // for use within the members of this struct
3172 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3173 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3174 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003175 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003176 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003177 if (filterMember(glslangMember))
3178 continue;
3179 }
John Kessenich6090df02016-06-30 21:18:02 -06003180
3181 // modify just this child's view of the qualifier
3182 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3183 InheritQualifiers(memberQualifier, qualifier);
3184
3185 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003186 if (member < 0)
3187 continue;
3188
3189 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3190 builder.addMemberDecoration(spvType, member,
3191 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3192 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3193 // Add interpolation and auxiliary storage decorations only to
3194 // top-level members of Input and Output storage classes
3195 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3196 type.getQualifier().storage == glslang::EvqVaryingOut) {
3197 if (type.getBasicType() == glslang::EbtBlock ||
3198 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3199 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3200 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003201#ifdef NV_EXTENSIONS
3202 addMeshNVDecoration(spvType, member, memberQualifier);
3203#endif
John Kessenich6090df02016-06-30 21:18:02 -06003204 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003205 }
3206 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003207
John Kessenich5d610ee2018-03-07 18:05:55 -07003208 if (type.getBasicType() == glslang::EbtBlock &&
3209 qualifier.storage == glslang::EvqBuffer) {
3210 // Add memory decorations only to top-level members of shader storage block
3211 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003212 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003213 for (unsigned int i = 0; i < memory.size(); ++i)
3214 builder.addMemberDecoration(spvType, member, memory[i]);
3215 }
John Kessenich6090df02016-06-30 21:18:02 -06003216
John Kessenich5d610ee2018-03-07 18:05:55 -07003217 // Location assignment was already completed correctly by the front end,
3218 // just track whether a member needs to be decorated.
3219 // Ignore member locations if the container is an array, as that's
3220 // ill-specified and decisions have been made to not allow this.
3221 if (! type.isArray() && memberQualifier.hasLocation())
3222 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003223
John Kessenich5d610ee2018-03-07 18:05:55 -07003224 if (qualifier.hasLocation()) // track for upcoming inheritance
3225 locationOffset += glslangIntermediate->computeTypeLocationSize(
3226 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003227
John Kessenich5d610ee2018-03-07 18:05:55 -07003228 // component, XFB, others
3229 if (glslangMember.getQualifier().hasComponent())
3230 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3231 glslangMember.getQualifier().layoutComponent);
3232 if (glslangMember.getQualifier().hasXfbOffset())
3233 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3234 glslangMember.getQualifier().layoutXfbOffset);
3235 else if (explicitLayout != glslang::ElpNone) {
3236 // figure out what to do with offset, which is accumulating
3237 int nextOffset;
3238 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3239 if (offset >= 0)
3240 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3241 offset = nextOffset;
3242 }
John Kessenich6090df02016-06-30 21:18:02 -06003243
John Kessenich5d610ee2018-03-07 18:05:55 -07003244 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3245 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3246 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003247
John Kessenich5d610ee2018-03-07 18:05:55 -07003248 // built-in variable decorations
3249 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3250 if (builtIn != spv::BuiltInMax)
3251 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003252
John Kessenich5611c6d2018-04-05 11:25:02 -06003253 // nonuniform
3254 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3255
John Kessenichead86222018-03-28 18:01:20 -06003256 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3257 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3258 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3259 memberQualifier.semanticName);
3260 }
3261
chaoc771d89f2017-01-13 01:10:53 -08003262#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003263 if (builtIn == spv::BuiltInLayer) {
3264 // SPV_NV_viewport_array2 extension
3265 if (glslangMember.getQualifier().layoutViewportRelative){
3266 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3267 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3268 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003269 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003270 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3271 builder.addMemberDecoration(spvType, member,
3272 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3273 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3274 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3275 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003276 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003277 }
3278 if (glslangMember.getQualifier().layoutPassthrough) {
3279 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3280 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3281 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3282 }
chaoc771d89f2017-01-13 01:10:53 -08003283#endif
John Kessenich6090df02016-06-30 21:18:02 -06003284 }
3285
3286 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003287 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3288 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003289}
3290
John Kessenich6c292d32016-02-15 20:58:50 -07003291// Turn the expression forming the array size into an id.
3292// This is not quite trivial, because of specialization constants.
3293// Sometimes, a raw constant is turned into an Id, and sometimes
3294// a specialization constant expression is.
3295spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3296{
3297 // First, see if this is sized with a node, meaning a specialization constant:
3298 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3299 if (specNode != nullptr) {
3300 builder.clearAccessChain();
3301 specNode->traverse(this);
3302 return accessChainLoad(specNode->getAsTyped()->getType());
3303 }
qining25262b32016-05-06 17:25:16 -04003304
John Kessenich6c292d32016-02-15 20:58:50 -07003305 // Otherwise, need a compile-time (front end) size, get it:
3306 int size = arraySizes.getDimSize(dim);
3307 assert(size > 0);
3308 return builder.makeUintConstant(size);
3309}
3310
John Kessenich103bef92016-02-08 21:38:15 -07003311// Wrap the builder's accessChainLoad to:
3312// - localize handling of RelaxedPrecision
3313// - use the SPIR-V inferred type instead of another conversion of the glslang type
3314// (avoids unnecessary work and possible type punning for structures)
3315// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003316spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3317{
John Kessenich103bef92016-02-08 21:38:15 -07003318 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003319
3320 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3321 coherentFlags |= TranslateCoherent(type);
3322
John Kessenich5611c6d2018-04-05 11:25:02 -06003323 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003324 TranslateNonUniformDecoration(type.getQualifier()),
3325 nominalTypeId,
3326 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3327 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003328
3329 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003330 if (type.getBasicType() == glslang::EbtBool) {
3331 if (builder.isScalarType(nominalTypeId)) {
3332 // Conversion for bool
3333 spv::Id boolType = builder.makeBoolType();
3334 if (nominalTypeId != boolType)
3335 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3336 } else if (builder.isVectorType(nominalTypeId)) {
3337 // Conversion for bvec
3338 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3339 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3340 if (nominalTypeId != bvecType)
3341 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3342 }
3343 }
John Kessenich103bef92016-02-08 21:38:15 -07003344
3345 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003346}
3347
Rex Xu27253232016-02-23 17:51:09 +08003348// Wrap the builder's accessChainStore to:
3349// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003350//
3351// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003352void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3353{
3354 // Need to convert to abstract types when necessary
3355 if (type.getBasicType() == glslang::EbtBool) {
3356 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3357
3358 if (builder.isScalarType(nominalTypeId)) {
3359 // Conversion for bool
3360 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003361 if (nominalTypeId != boolType) {
3362 // keep these outside arguments, for determinant order-of-evaluation
3363 spv::Id one = builder.makeUintConstant(1);
3364 spv::Id zero = builder.makeUintConstant(0);
3365 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3366 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003367 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003368 } else if (builder.isVectorType(nominalTypeId)) {
3369 // Conversion for bvec
3370 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3371 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003372 if (nominalTypeId != bvecType) {
3373 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003374 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3375 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3376 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003377 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003378 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3379 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003380 }
3381 }
3382
Jeff Bolz36831c92018-09-05 10:11:41 -05003383 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3384 coherentFlags |= TranslateCoherent(type);
3385
3386 builder.accessChainStore(rvalue,
3387 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3388 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003389}
3390
John Kessenich4bf71552016-09-02 11:20:21 -06003391// For storing when types match at the glslang level, but not might match at the
3392// SPIR-V level.
3393//
3394// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003395// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003396// as in a member-decorated way.
3397//
3398// NOTE: This function can handle any store request; if it's not special it
3399// simplifies to a simple OpStore.
3400//
3401// Implicitly uses the existing builder.accessChain as the storage target.
3402void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3403{
John Kessenichb3e24e42016-09-11 12:33:43 -06003404 // we only do the complex path here if it's an aggregate
3405 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003406 accessChainStore(type, rValue);
3407 return;
3408 }
3409
John Kessenichb3e24e42016-09-11 12:33:43 -06003410 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003411 spv::Id rType = builder.getTypeId(rValue);
3412 spv::Id lValue = builder.accessChainGetLValue();
3413 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3414 if (lType == rType) {
3415 accessChainStore(type, rValue);
3416 return;
3417 }
3418
John Kessenichb3e24e42016-09-11 12:33:43 -06003419 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003420 // where the two types were the same type in GLSL. This requires member
3421 // by member copy, recursively.
3422
John Kessenichb3e24e42016-09-11 12:33:43 -06003423 // If an array, copy element by element.
3424 if (type.isArray()) {
3425 glslang::TType glslangElementType(type, 0);
3426 spv::Id elementRType = builder.getContainedTypeId(rType);
3427 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3428 // get the source member
3429 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003430
John Kessenichb3e24e42016-09-11 12:33:43 -06003431 // set up the target storage
3432 builder.clearAccessChain();
3433 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003434 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003435
John Kessenichb3e24e42016-09-11 12:33:43 -06003436 // store the member
3437 multiTypeStore(glslangElementType, elementRValue);
3438 }
3439 } else {
3440 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003441
John Kessenichb3e24e42016-09-11 12:33:43 -06003442 // loop over structure members
3443 const glslang::TTypeList& members = *type.getStruct();
3444 for (int m = 0; m < (int)members.size(); ++m) {
3445 const glslang::TType& glslangMemberType = *members[m].type;
3446
3447 // get the source member
3448 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3449 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3450
3451 // set up the target storage
3452 builder.clearAccessChain();
3453 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003454 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003455
3456 // store the member
3457 multiTypeStore(glslangMemberType, memberRValue);
3458 }
John Kessenich4bf71552016-09-02 11:20:21 -06003459 }
3460}
3461
John Kessenichf85e8062015-12-19 13:57:10 -07003462// Decide whether or not this type should be
3463// decorated with offsets and strides, and if so
3464// whether std140 or std430 rules should be applied.
3465glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003466{
John Kessenichf85e8062015-12-19 13:57:10 -07003467 // has to be a block
3468 if (type.getBasicType() != glslang::EbtBlock)
3469 return glslang::ElpNone;
3470
Chao Chen3c366992018-09-19 11:41:59 -07003471 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003472 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003473 type.getQualifier().storage != glslang::EvqBuffer &&
3474 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003475 return glslang::ElpNone;
3476
3477 // return the layout to use
3478 switch (type.getQualifier().layoutPacking) {
3479 case glslang::ElpStd140:
3480 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003481 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003482 return type.getQualifier().layoutPacking;
3483 default:
3484 return glslang::ElpNone;
3485 }
John Kessenich31ed4832015-09-09 17:51:38 -06003486}
3487
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003488// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003489int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003490{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003491 int size;
John Kessenich49987892015-12-29 17:11:44 -07003492 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003493 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003494
3495 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003496}
3497
John Kessenich49987892015-12-29 17:11:44 -07003498// 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 -07003499// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003500int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003501{
John Kessenich49987892015-12-29 17:11:44 -07003502 glslang::TType elementType;
3503 elementType.shallowCopy(matrixType);
3504 elementType.clearArraySizes();
3505
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003506 int size;
John Kessenich49987892015-12-29 17:11:44 -07003507 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003508 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003509
3510 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003511}
3512
John Kessenich5e4b1242015-08-06 22:53:06 -06003513// Given a member type of a struct, realign the current offset for it, and compute
3514// the next (not yet aligned) offset for the next member, which will get aligned
3515// on the next call.
3516// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3517// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3518// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003519void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003520 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003521{
3522 // this will get a positive value when deemed necessary
3523 nextOffset = -1;
3524
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 // override anything in currentOffset with user-set offset
3526 if (memberType.getQualifier().hasOffset())
3527 currentOffset = memberType.getQualifier().layoutOffset;
3528
3529 // It could be that current linker usage in glslang updated all the layoutOffset,
3530 // in which case the following code does not matter. But, that's not quite right
3531 // once cross-compilation unit GLSL validation is done, as the original user
3532 // settings are needed in layoutOffset, and then the following will come into play.
3533
John Kessenichf85e8062015-12-19 13:57:10 -07003534 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 if (! memberType.getQualifier().hasOffset())
3536 currentOffset = -1;
3537
3538 return;
3539 }
3540
John Kessenichf85e8062015-12-19 13:57:10 -07003541 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003542 if (currentOffset < 0)
3543 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003544
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3546 // but possibly not yet correctly aligned.
3547
3548 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003549 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003550 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003551
3552 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003553 // TODO: make this consistent in early phases of code:
3554 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3555 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3556 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003557 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003558 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003559 int dummySize;
3560 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3561 if (componentAlignment <= 4)
3562 memberAlignment = componentAlignment;
3563 }
3564
3565 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003567
3568 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003569 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003570 glslang::RoundToPow2(currentOffset, 16);
3571
John Kessenich5e4b1242015-08-06 22:53:06 -06003572 nextOffset = currentOffset + memberSize;
3573}
3574
David Netoa901ffe2016-06-08 14:11:40 +01003575void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003576{
David Netoa901ffe2016-06-08 14:11:40 +01003577 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3578 switch (glslangBuiltIn)
3579 {
3580 case glslang::EbvClipDistance:
3581 case glslang::EbvCullDistance:
3582 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003583#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003584 case glslang::EbvViewportMaskNV:
3585 case glslang::EbvSecondaryPositionNV:
3586 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003587 case glslang::EbvPositionPerViewNV:
3588 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003589 case glslang::EbvTaskCountNV:
3590 case glslang::EbvPrimitiveCountNV:
3591 case glslang::EbvPrimitiveIndicesNV:
3592 case glslang::EbvClipDistancePerViewNV:
3593 case glslang::EbvCullDistancePerViewNV:
3594 case glslang::EbvLayerPerViewNV:
3595 case glslang::EbvMeshViewCountNV:
3596 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003597#endif
David Netoa901ffe2016-06-08 14:11:40 +01003598 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3599 // Alternately, we could just call this for any glslang built-in, since the
3600 // capability already guards against duplicates.
3601 TranslateBuiltInDecoration(glslangBuiltIn, false);
3602 break;
3603 default:
3604 // Capabilities were already generated when the struct was declared.
3605 break;
3606 }
John Kessenichebb50532016-05-16 19:22:05 -06003607}
3608
John Kessenich6fccb3c2016-09-19 16:01:41 -06003609bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003610{
John Kessenicheee9d532016-09-19 18:09:30 -06003611 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003612}
3613
John Kessenichd41993d2017-09-10 15:21:05 -06003614// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003615// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3616// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003617bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003618{
John Kessenich6a14f782017-12-04 02:48:10 -07003619 assert(qualifier == glslang::EvqIn ||
3620 qualifier == glslang::EvqOut ||
3621 qualifier == glslang::EvqInOut ||
3622 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003623 return qualifier != glslang::EvqConstReadOnly;
3624}
3625
3626// Is parameter pass-by-original?
3627bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3628 bool implicitThisParam)
3629{
3630 if (implicitThisParam) // implicit this
3631 return true;
3632 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003633 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003634 return paramType.containsOpaque() || // sampler, etc.
3635 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3636}
3637
John Kessenich140f3df2015-06-26 16:58:36 -06003638// Make all the functions, skeletally, without actually visiting their bodies.
3639void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3640{
Jeff Bolz36831c92018-09-05 10:11:41 -05003641 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003642 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3643 if (paramPrecision != spv::NoPrecision)
3644 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003645 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003646 };
3647
John Kessenich140f3df2015-06-26 16:58:36 -06003648 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3649 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003650 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003651 continue;
3652
3653 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003654 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003655 //
qining25262b32016-05-06 17:25:16 -04003656 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003657 // function. What it is an address of varies:
3658 //
John Kessenich4bf71552016-09-02 11:20:21 -06003659 // - "in" parameters not marked as "const" can be written to without modifying the calling
3660 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003661 //
3662 // - "const in" parameters can just be the r-value, as no writes need occur.
3663 //
John Kessenich4bf71552016-09-02 11:20:21 -06003664 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3665 // 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 -06003666
3667 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003668 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003669 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3670
John Kessenichfad62972017-07-18 02:35:46 -06003671 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3672 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003673
John Kessenichfad62972017-07-18 02:35:46 -06003674 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003675 for (int p = 0; p < (int)parameters.size(); ++p) {
3676 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3677 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003678 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003679 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003680 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003681 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3682 else
John Kessenich4bf71552016-09-02 11:20:21 -06003683 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003684 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003685 paramTypes.push_back(typeId);
3686 }
3687
3688 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003689 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3690 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003691 glslFunction->getName().c_str(), paramTypes,
3692 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003693 if (implicitThis)
3694 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003695
3696 // Track function to emit/call later
3697 functionMap[glslFunction->getName().c_str()] = function;
3698
3699 // Set the parameter id's
3700 for (int p = 0; p < (int)parameters.size(); ++p) {
3701 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3702 // give a name too
3703 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3704 }
3705 }
3706}
3707
3708// Process all the initializers, while skipping the functions and link objects
3709void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3710{
3711 builder.setBuildPoint(shaderEntry->getLastBlock());
3712 for (int i = 0; i < (int)initializers.size(); ++i) {
3713 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3714 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3715
3716 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003717 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003718 initializer->traverse(this);
3719 }
3720 }
3721}
3722
3723// Process all the functions, while skipping initializers.
3724void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3725{
3726 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3727 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003728 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003729 node->traverse(this);
3730 }
3731}
3732
3733void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3734{
qining25262b32016-05-06 17:25:16 -04003735 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003736 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003737 currentFunction = functionMap[node->getName().c_str()];
3738 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003739 builder.setBuildPoint(functionBlock);
3740}
3741
Rex Xu04db3f52015-09-16 11:44:02 +08003742void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003743{
Rex Xufc618912015-09-09 16:42:49 +08003744 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003745
3746 glslang::TSampler sampler = {};
3747 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003748#ifdef AMD_EXTENSIONS
3749 bool f16ShadowCompare = false;
3750#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003751 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003752 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3753 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003754#ifdef AMD_EXTENSIONS
3755 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3756#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003757 }
3758
John Kessenich140f3df2015-06-26 16:58:36 -06003759 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3760 builder.clearAccessChain();
3761 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003762
3763 // Special case l-value operands
3764 bool lvalue = false;
3765 switch (node.getOp()) {
3766 case glslang::EOpImageAtomicAdd:
3767 case glslang::EOpImageAtomicMin:
3768 case glslang::EOpImageAtomicMax:
3769 case glslang::EOpImageAtomicAnd:
3770 case glslang::EOpImageAtomicOr:
3771 case glslang::EOpImageAtomicXor:
3772 case glslang::EOpImageAtomicExchange:
3773 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003774 case glslang::EOpImageAtomicLoad:
3775 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003776 if (i == 0)
3777 lvalue = true;
3778 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003779 case glslang::EOpSparseImageLoad:
3780 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3781 lvalue = true;
3782 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003783#ifdef AMD_EXTENSIONS
3784 case glslang::EOpSparseTexture:
3785 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3786 lvalue = true;
3787 break;
3788 case glslang::EOpSparseTextureClamp:
3789 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3790 lvalue = true;
3791 break;
3792 case glslang::EOpSparseTextureLod:
3793 case glslang::EOpSparseTextureOffset:
3794 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3795 lvalue = true;
3796 break;
3797#else
Rex Xu48edadf2015-12-31 16:11:41 +08003798 case glslang::EOpSparseTexture:
3799 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3800 lvalue = true;
3801 break;
3802 case glslang::EOpSparseTextureClamp:
3803 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3804 lvalue = true;
3805 break;
3806 case glslang::EOpSparseTextureLod:
3807 case glslang::EOpSparseTextureOffset:
3808 if (i == 3)
3809 lvalue = true;
3810 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003811#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003812 case glslang::EOpSparseTextureFetch:
3813 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3814 lvalue = true;
3815 break;
3816 case glslang::EOpSparseTextureFetchOffset:
3817 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3818 lvalue = true;
3819 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003820#ifdef AMD_EXTENSIONS
3821 case glslang::EOpSparseTextureLodOffset:
3822 case glslang::EOpSparseTextureGrad:
3823 case glslang::EOpSparseTextureOffsetClamp:
3824 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3825 lvalue = true;
3826 break;
3827 case glslang::EOpSparseTextureGradOffset:
3828 case glslang::EOpSparseTextureGradClamp:
3829 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3830 lvalue = true;
3831 break;
3832 case glslang::EOpSparseTextureGradOffsetClamp:
3833 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3834 lvalue = true;
3835 break;
3836#else
Rex Xu48edadf2015-12-31 16:11:41 +08003837 case glslang::EOpSparseTextureLodOffset:
3838 case glslang::EOpSparseTextureGrad:
3839 case glslang::EOpSparseTextureOffsetClamp:
3840 if (i == 4)
3841 lvalue = true;
3842 break;
3843 case glslang::EOpSparseTextureGradOffset:
3844 case glslang::EOpSparseTextureGradClamp:
3845 if (i == 5)
3846 lvalue = true;
3847 break;
3848 case glslang::EOpSparseTextureGradOffsetClamp:
3849 if (i == 6)
3850 lvalue = true;
3851 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003852#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003853 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003854 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3855 lvalue = true;
3856 break;
3857 case glslang::EOpSparseTextureGatherOffset:
3858 case glslang::EOpSparseTextureGatherOffsets:
3859 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3860 lvalue = true;
3861 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003862#ifdef AMD_EXTENSIONS
3863 case glslang::EOpSparseTextureGatherLod:
3864 if (i == 3)
3865 lvalue = true;
3866 break;
3867 case glslang::EOpSparseTextureGatherLodOffset:
3868 case glslang::EOpSparseTextureGatherLodOffsets:
3869 if (i == 4)
3870 lvalue = true;
3871 break;
Rex Xu129799a2017-07-05 17:23:28 +08003872 case glslang::EOpSparseImageLoadLod:
3873 if (i == 3)
3874 lvalue = true;
3875 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003876#endif
Chao Chen3a137962018-09-19 11:41:27 -07003877#ifdef NV_EXTENSIONS
3878 case glslang::EOpImageSampleFootprintNV:
3879 if (i == 4)
3880 lvalue = true;
3881 break;
3882 case glslang::EOpImageSampleFootprintClampNV:
3883 case glslang::EOpImageSampleFootprintLodNV:
3884 if (i == 5)
3885 lvalue = true;
3886 break;
3887 case glslang::EOpImageSampleFootprintGradNV:
3888 if (i == 6)
3889 lvalue = true;
3890 break;
3891 case glslang::EOpImageSampleFootprintGradClampNV:
3892 if (i == 7)
3893 lvalue = true;
3894 break;
3895#endif
Rex Xufc618912015-09-09 16:42:49 +08003896 default:
3897 break;
3898 }
3899
Rex Xu6b86d492015-09-16 17:48:22 +08003900 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003901 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003902 else
John Kessenich32cfd492016-02-02 12:37:46 -07003903 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003904 }
3905}
3906
John Kessenichfc51d282015-08-19 13:34:18 -06003907void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003908{
John Kessenichfc51d282015-08-19 13:34:18 -06003909 builder.clearAccessChain();
3910 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003911 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003912}
John Kessenich140f3df2015-06-26 16:58:36 -06003913
John Kessenichfc51d282015-08-19 13:34:18 -06003914spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3915{
John Kesseniche485c7a2017-05-31 18:50:53 -06003916 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003917 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003918
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003919 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003920
John Kessenichfc51d282015-08-19 13:34:18 -06003921 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003922
3923 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3924 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3925 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003926#ifdef AMD_EXTENSIONS
3927 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3928 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3929 : false;
3930#endif
3931
John Kessenichfc51d282015-08-19 13:34:18 -06003932 std::vector<spv::Id> arguments;
3933 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003934 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003935 else
3936 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003937 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003938
3939 spv::Builder::TextureParameters params = { };
3940 params.sampler = arguments[0];
3941
Rex Xu04db3f52015-09-16 11:44:02 +08003942 glslang::TCrackedTextureOp cracked;
3943 node->crackTexture(sampler, cracked);
3944
amhagan05506bb2017-06-13 16:53:02 -04003945 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003946
John Kessenichfc51d282015-08-19 13:34:18 -06003947 // Check for queries
3948 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003949 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3950 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003951 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003952
John Kessenichfc51d282015-08-19 13:34:18 -06003953 switch (node->getOp()) {
3954 case glslang::EOpImageQuerySize:
3955 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003956 if (arguments.size() > 1) {
3957 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003958 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003959 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003960 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003961 case glslang::EOpImageQuerySamples:
3962 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003963 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003964 case glslang::EOpTextureQueryLod:
3965 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003966 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003967 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003968 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003969 case glslang::EOpSparseTexelsResident:
3970 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003971 default:
3972 assert(0);
3973 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003974 }
John Kessenich140f3df2015-06-26 16:58:36 -06003975 }
3976
LoopDawg4425f242018-02-18 11:40:01 -07003977 int components = node->getType().getVectorSize();
3978
3979 if (node->getOp() == glslang::EOpTextureFetch) {
3980 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3981 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3982 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3983 // here around e.g. which ones return scalars or other types.
3984 components = 4;
3985 }
3986
3987 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3988
3989 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3990
Rex Xufc618912015-09-09 16:42:49 +08003991 // Check for image functions other than queries
3992 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003993 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003994 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003995 spv::IdImmediate image = { true, *(opIt++) };
3996 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003997
3998 // Handle subpass operations
3999 // TODO: GLSL should change to have the "MS" only on the type rather than the
4000 // built-in function.
4001 if (cracked.subpass) {
4002 // add on the (0,0) coordinate
4003 spv::Id zero = builder.makeIntConstant(0);
4004 std::vector<spv::Id> comps;
4005 comps.push_back(zero);
4006 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004007 spv::IdImmediate coord = { true,
4008 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4009 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004010 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004011 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4012 operands.push_back(imageOperands);
4013 spv::IdImmediate imageOperand = { true, *(opIt++) };
4014 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004015 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004016 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4017 builder.setPrecision(result, precision);
4018 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004019 }
4020
John Kessenich149afc32018-08-14 13:31:43 -06004021 spv::IdImmediate coord = { true, *(opIt++) };
4022 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004023#ifdef AMD_EXTENSIONS
4024 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4025#else
John Kessenich56bab042015-09-16 10:54:31 -06004026 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004027#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004028 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004029 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004030 mask = mask | spv::ImageOperandsSampleMask;
4031 }
Rex Xu129799a2017-07-05 17:23:28 +08004032#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004033 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004034 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4035 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004036 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004037 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004038#endif
4039 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4040 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4041 if (mask) {
4042 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4043 operands.push_back(imageOperands);
4044 }
4045 if (mask & spv::ImageOperandsSampleMask) {
4046 spv::IdImmediate imageOperand = { true, *opIt++ };
4047 operands.push_back(imageOperand);
4048 }
4049#ifdef AMD_EXTENSIONS
4050 if (mask & spv::ImageOperandsLodMask) {
4051 spv::IdImmediate imageOperand = { true, *opIt++ };
4052 operands.push_back(imageOperand);
4053 }
4054#endif
4055 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4056 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4057 operands.push_back(imageOperand);
4058 }
4059
John Kessenich149afc32018-08-14 13:31:43 -06004060 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004061 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004062
John Kessenich149afc32018-08-14 13:31:43 -06004063 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004064 builder.setPrecision(result[0], precision);
4065
4066 // If needed, add a conversion constructor to the proper size.
4067 if (components != node->getType().getVectorSize())
4068 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4069
4070 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004071#ifdef AMD_EXTENSIONS
4072 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4073#else
John Kessenich56bab042015-09-16 10:54:31 -06004074 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004075#endif
Rex Xu129799a2017-07-05 17:23:28 +08004076
Jeff Bolz36831c92018-09-05 10:11:41 -05004077 // Push the texel value before the operands
4078#ifdef AMD_EXTENSIONS
4079 if (sampler.ms || cracked.lod) {
4080#else
4081 if (sampler.ms) {
4082#endif
John Kessenich149afc32018-08-14 13:31:43 -06004083 spv::IdImmediate texel = { true, *(opIt + 1) };
4084 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004085 } else {
4086 spv::IdImmediate texel = { true, *opIt };
4087 operands.push_back(texel);
4088 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004089
4090 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4091 if (sampler.ms) {
4092 mask = mask | spv::ImageOperandsSampleMask;
4093 }
4094#ifdef AMD_EXTENSIONS
4095 if (cracked.lod) {
4096 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4097 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4098 mask = mask | spv::ImageOperandsLodMask;
4099 }
4100#endif
4101 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4102 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4103 if (mask) {
4104 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4105 operands.push_back(imageOperands);
4106 }
4107 if (mask & spv::ImageOperandsSampleMask) {
4108 spv::IdImmediate imageOperand = { true, *opIt++ };
4109 operands.push_back(imageOperand);
4110 }
4111#ifdef AMD_EXTENSIONS
4112 if (mask & spv::ImageOperandsLodMask) {
4113 spv::IdImmediate imageOperand = { true, *opIt++ };
4114 operands.push_back(imageOperand);
4115 }
4116#endif
4117 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4118 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4119 operands.push_back(imageOperand);
4120 }
4121
John Kessenich56bab042015-09-16 10:54:31 -06004122 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004123 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004124 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004125 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004126#ifdef AMD_EXTENSIONS
4127 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4128#else
Rex Xu5eafa472016-02-19 22:24:03 +08004129 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004130#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004131 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004132 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004133 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4134
Jeff Bolz36831c92018-09-05 10:11:41 -05004135 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004136 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004137 mask = mask | spv::ImageOperandsSampleMask;
4138 }
Rex Xu129799a2017-07-05 17:23:28 +08004139#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004140 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004141 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4142 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4143
Jeff Bolz36831c92018-09-05 10:11:41 -05004144 mask = mask | spv::ImageOperandsLodMask;
4145 }
4146#endif
4147 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4148 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4149 if (mask) {
4150 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004151 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004152 }
4153 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004154 spv::IdImmediate imageOperand = { true, *opIt++ };
4155 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004156 }
4157#ifdef AMD_EXTENSIONS
4158 if (mask & spv::ImageOperandsLodMask) {
4159 spv::IdImmediate imageOperand = { true, *opIt++ };
4160 operands.push_back(imageOperand);
4161 }
Rex Xu129799a2017-07-05 17:23:28 +08004162#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004163 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4164 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4165 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004166 }
4167
4168 // Create the return type that was a special structure
4169 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004170 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004171 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4172 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4173
4174 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4175
4176 // Decode the return type
4177 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4178 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004179 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004180 // Process image atomic operations
4181
4182 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4183 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004184 // For non-MS, the sample value should be 0
4185 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4186 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004187
Jeff Bolz36831c92018-09-05 10:11:41 -05004188 spv::Id resultTypeId;
4189 // imageAtomicStore has a void return type so base the pointer type on
4190 // the type of the value operand.
4191 if (node->getOp() == glslang::EOpImageAtomicStore) {
4192 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4193 } else {
4194 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4195 }
John Kessenich56bab042015-09-16 10:54:31 -06004196 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004197
4198 std::vector<spv::Id> operands;
4199 operands.push_back(pointer);
4200 for (; opIt != arguments.end(); ++opIt)
4201 operands.push_back(*opIt);
4202
John Kessenich8c8505c2016-07-26 12:50:38 -06004203 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004204 }
4205 }
4206
amhagan05506bb2017-06-13 16:53:02 -04004207#ifdef AMD_EXTENSIONS
4208 // Check for fragment mask functions other than queries
4209 if (cracked.fragMask) {
4210 assert(sampler.ms);
4211
4212 auto opIt = arguments.begin();
4213 std::vector<spv::Id> operands;
4214
4215 // Extract the image if necessary
4216 if (builder.isSampledImage(params.sampler))
4217 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4218
4219 operands.push_back(params.sampler);
4220 ++opIt;
4221
4222 if (sampler.isSubpass()) {
4223 // add on the (0,0) coordinate
4224 spv::Id zero = builder.makeIntConstant(0);
4225 std::vector<spv::Id> comps;
4226 comps.push_back(zero);
4227 comps.push_back(zero);
4228 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4229 }
4230
4231 for (; opIt != arguments.end(); ++opIt)
4232 operands.push_back(*opIt);
4233
4234 spv::Op fragMaskOp = spv::OpNop;
4235 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4236 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4237 else if (node->getOp() == glslang::EOpFragmentFetch)
4238 fragMaskOp = spv::OpFragmentFetchAMD;
4239
4240 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4241 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4242 return builder.createOp(fragMaskOp, resultType(), operands);
4243 }
4244#endif
4245
Rex Xufc618912015-09-09 16:42:49 +08004246 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004247 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004248#ifdef NV_EXTENSIONS
4249 bool imageFootprint = node->isImageFootprint();
4250#endif
4251
Rex Xu71519fe2015-11-11 15:35:47 +08004252 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4253
John Kessenichfc51d282015-08-19 13:34:18 -06004254 // check for bias argument
4255 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004256#ifdef AMD_EXTENSIONS
4257 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4258#else
Rex Xu71519fe2015-11-11 15:35:47 +08004259 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004260#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004261 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004262#ifdef AMD_EXTENSIONS
4263 if (cracked.gather)
4264 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004265
4266 if (f16ShadowCompare)
4267 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004268#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004269 if (cracked.offset)
4270 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004271#ifdef AMD_EXTENSIONS
4272 else if (cracked.offsets)
4273 ++nonBiasArgCount;
4274#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004275 if (cracked.grad)
4276 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004277 if (cracked.lodClamp)
4278 ++nonBiasArgCount;
4279 if (sparse)
4280 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004281#ifdef NV_EXTENSIONS
4282 if (imageFootprint)
4283 //Following three extra arguments
4284 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4285 nonBiasArgCount += 3;
4286#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004287 if ((int)arguments.size() > nonBiasArgCount)
4288 bias = true;
4289 }
4290
John Kessenicha5c33d62016-06-02 23:45:21 -06004291 // See if the sampler param should really be just the SPV image part
4292 if (cracked.fetch) {
4293 // a fetch needs to have the image extracted first
4294 if (builder.isSampledImage(params.sampler))
4295 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4296 }
4297
Rex Xu225e0fc2016-11-17 17:47:59 +08004298#ifdef AMD_EXTENSIONS
4299 if (cracked.gather) {
4300 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4301 if (bias || cracked.lod ||
4302 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4303 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004304 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004305 }
4306 }
4307#endif
4308
John Kessenichfc51d282015-08-19 13:34:18 -06004309 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004310
John Kessenichfc51d282015-08-19 13:34:18 -06004311 params.coords = arguments[1];
4312 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004313 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004314
4315 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004316#ifdef AMD_EXTENSIONS
4317 if (cubeCompare || f16ShadowCompare) {
4318#else
Rex Xu48edadf2015-12-31 16:11:41 +08004319 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004320#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004321 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004322 ++extraArgs;
4323 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004324 params.Dref = arguments[2];
4325 ++extraArgs;
4326 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004327 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004328 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004329 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004330 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004331 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004332 dRefComp = builder.getNumComponents(params.coords) - 1;
4333 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004334 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4335 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004336
4337 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004338 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004339 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004340 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004341 } else if (glslangIntermediate->getStage() != EShLangFragment
4342#ifdef NV_EXTENSIONS
4343 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4344 && !(glslangIntermediate->getStage() == EShLangCompute &&
4345 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4346#endif
4347 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004348 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4349 noImplicitLod = true;
4350 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004351
4352 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004353 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004354 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004355 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004356 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004357
4358 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004359 if (cracked.grad) {
4360 params.gradX = arguments[2 + extraArgs];
4361 params.gradY = arguments[3 + extraArgs];
4362 extraArgs += 2;
4363 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004364
4365 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004366 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004367 params.offset = arguments[2 + extraArgs];
4368 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004369 } else if (cracked.offsets) {
4370 params.offsets = arguments[2 + extraArgs];
4371 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004372 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004373
4374 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004375 if (cracked.lodClamp) {
4376 params.lodClamp = arguments[2 + extraArgs];
4377 ++extraArgs;
4378 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004379 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004380 if (sparse) {
4381 params.texelOut = arguments[2 + extraArgs];
4382 ++extraArgs;
4383 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004384
John Kessenich76d4dfc2016-06-16 12:43:23 -06004385 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004386 if (cracked.gather && ! sampler.shadow) {
4387 // default component is 0, if missing, otherwise an argument
4388 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004389 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004390 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004391 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004392 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004393 }
Chao Chen3a137962018-09-19 11:41:27 -07004394#ifdef NV_EXTENSIONS
4395 spv::Id resultStruct = spv::NoResult;
4396 if (imageFootprint) {
4397 //Following three extra arguments
4398 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4399 params.granularity = arguments[2 + extraArgs];
4400 params.coarse = arguments[3 + extraArgs];
4401 resultStruct = arguments[4 + extraArgs];
4402 extraArgs += 3;
4403 }
4404#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004405 // bias
4406 if (bias) {
4407 params.bias = arguments[2 + extraArgs];
4408 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004409 }
John Kessenichfc51d282015-08-19 13:34:18 -06004410
Chao Chen3a137962018-09-19 11:41:27 -07004411#ifdef NV_EXTENSIONS
4412 if (imageFootprint) {
4413 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4414 builder.addCapability(spv::CapabilityImageFootprintNV);
4415
4416
4417 //resultStructType(OpenGL type) contains 5 elements:
4418 //struct gl_TextureFootprint2DNV {
4419 // uvec2 anchor;
4420 // uvec2 offset;
4421 // uvec2 mask;
4422 // uint lod;
4423 // uint granularity;
4424 //};
4425 //or
4426 //struct gl_TextureFootprint3DNV {
4427 // uvec3 anchor;
4428 // uvec3 offset;
4429 // uvec2 mask;
4430 // uint lod;
4431 // uint granularity;
4432 //};
4433 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4434 assert(builder.isStructType(resultStructType));
4435
4436 //resType (SPIR-V type) contains 6 elements:
4437 //Member 0 must be a Boolean type scalar(LOD),
4438 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4439 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4440 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4441 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4442 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4443 std::vector<spv::Id> members;
4444 members.push_back(resultType());
4445 for (int i = 0; i < 5; i++) {
4446 members.push_back(builder.getContainedTypeId(resultStructType, i));
4447 }
4448 spv::Id resType = builder.makeStructType(members, "ResType");
4449
4450 //call ImageFootprintNV
4451 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4452
4453 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4454 for (int i = 0; i < 5; i++) {
4455 builder.clearAccessChain();
4456 builder.setAccessChainLValue(resultStruct);
4457
4458 //Accessing to a struct we created, no coherent flag is set
4459 spv::Builder::AccessChain::CoherentFlags flags;
4460 flags.clear();
4461
4462 builder.accessChainPush(builder.makeIntConstant(i), flags);
4463 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4464 }
4465 return builder.createCompositeExtract(res, resultType(), 0);
4466 }
4467#endif
4468
John Kessenich65336482016-06-16 14:06:26 -06004469 // projective component (might not to move)
4470 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4471 // are divided by the last component of P."
4472 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4473 // unused components will appear after all used components."
4474 if (cracked.proj) {
4475 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4476 int projTargetComp;
4477 switch (sampler.dim) {
4478 case glslang::Esd1D: projTargetComp = 1; break;
4479 case glslang::Esd2D: projTargetComp = 2; break;
4480 case glslang::EsdRect: projTargetComp = 2; break;
4481 default: projTargetComp = projSourceComp; break;
4482 }
4483 // copy the projective coordinate if we have to
4484 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004485 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004486 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4487 projSourceComp);
4488 params.coords = builder.createCompositeInsert(projComp, params.coords,
4489 builder.getTypeId(params.coords), projTargetComp);
4490 }
4491 }
4492
Jeff Bolz36831c92018-09-05 10:11:41 -05004493 // nonprivate
4494 if (imageType.getQualifier().nonprivate) {
4495 params.nonprivate = true;
4496 }
4497
4498 // volatile
4499 if (imageType.getQualifier().volatil) {
4500 params.volatil = true;
4501 }
4502
St0fFa1184dd2018-04-09 21:08:14 +02004503 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004504 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004505 );
LoopDawg4425f242018-02-18 11:40:01 -07004506
4507 if (components != node->getType().getVectorSize())
4508 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4509
4510 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004511}
4512
4513spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4514{
4515 // Grab the function's pointer from the previously created function
4516 spv::Function* function = functionMap[node->getName().c_str()];
4517 if (! function)
4518 return 0;
4519
4520 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4521 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4522
4523 // See comments in makeFunctions() for details about the semantics for parameter passing.
4524 //
4525 // These imply we need a four step process:
4526 // 1. Evaluate the arguments
4527 // 2. Allocate and make copies of in, out, and inout arguments
4528 // 3. Make the call
4529 // 4. Copy back the results
4530
John Kessenichd3ed90b2018-05-04 11:43:03 -06004531 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004532 std::vector<spv::Builder::AccessChain> lValues;
4533 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004534 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004535 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004536 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004537 // build l-value
4538 builder.clearAccessChain();
4539 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004540 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004541 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004542 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004543 // save l-value
4544 lValues.push_back(builder.getAccessChain());
4545 } else {
4546 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004547 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004548 }
4549 }
4550
4551 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4552 // copy the original into that space.
4553 //
4554 // Also, build up the list of actual arguments to pass in for the call
4555 int lValueCount = 0;
4556 int rValueCount = 0;
4557 std::vector<spv::Id> spvArgs;
4558 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4559 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004560 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004561 builder.setAccessChain(lValues[lValueCount]);
4562 arg = builder.accessChainGetLValue();
4563 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004564 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004565 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004566 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004567 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4568 // need to copy the input into output space
4569 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004570 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004571 builder.clearAccessChain();
4572 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004573 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004574 }
4575 ++lValueCount;
4576 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004577 // process r-value, which involves a copy for a type mismatch
4578 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4579 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4580 builder.clearAccessChain();
4581 builder.setAccessChainLValue(argCopy);
4582 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4583 arg = builder.createLoad(argCopy);
4584 } else
4585 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004586 ++rValueCount;
4587 }
4588 spvArgs.push_back(arg);
4589 }
4590
4591 // 3. Make the call.
4592 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004593 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004594
4595 // 4. Copy back out an "out" arguments.
4596 lValueCount = 0;
4597 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004598 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004599 ++lValueCount;
4600 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004601 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4602 spv::Id copy = builder.createLoad(spvArgs[a]);
4603 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004604 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004605 }
4606 ++lValueCount;
4607 }
4608 }
4609
4610 return result;
4611}
4612
4613// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004614spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004615 spv::Id typeId, spv::Id left, spv::Id right,
4616 glslang::TBasicType typeProxy, bool reduceComparison)
4617{
John Kessenich66011cb2018-03-06 16:12:04 -07004618 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4619 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004620 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004621
4622 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004623 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004624 bool comparison = false;
4625
4626 switch (op) {
4627 case glslang::EOpAdd:
4628 case glslang::EOpAddAssign:
4629 if (isFloat)
4630 binOp = spv::OpFAdd;
4631 else
4632 binOp = spv::OpIAdd;
4633 break;
4634 case glslang::EOpSub:
4635 case glslang::EOpSubAssign:
4636 if (isFloat)
4637 binOp = spv::OpFSub;
4638 else
4639 binOp = spv::OpISub;
4640 break;
4641 case glslang::EOpMul:
4642 case glslang::EOpMulAssign:
4643 if (isFloat)
4644 binOp = spv::OpFMul;
4645 else
4646 binOp = spv::OpIMul;
4647 break;
4648 case glslang::EOpVectorTimesScalar:
4649 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004650 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004651 if (builder.isVector(right))
4652 std::swap(left, right);
4653 assert(builder.isScalar(right));
4654 needMatchingVectors = false;
4655 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004656 } else if (isFloat)
4657 binOp = spv::OpFMul;
4658 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004659 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004660 break;
4661 case glslang::EOpVectorTimesMatrix:
4662 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004663 binOp = spv::OpVectorTimesMatrix;
4664 break;
4665 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004666 binOp = spv::OpMatrixTimesVector;
4667 break;
4668 case glslang::EOpMatrixTimesScalar:
4669 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004670 binOp = spv::OpMatrixTimesScalar;
4671 break;
4672 case glslang::EOpMatrixTimesMatrix:
4673 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004674 binOp = spv::OpMatrixTimesMatrix;
4675 break;
4676 case glslang::EOpOuterProduct:
4677 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004678 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004679 break;
4680
4681 case glslang::EOpDiv:
4682 case glslang::EOpDivAssign:
4683 if (isFloat)
4684 binOp = spv::OpFDiv;
4685 else if (isUnsigned)
4686 binOp = spv::OpUDiv;
4687 else
4688 binOp = spv::OpSDiv;
4689 break;
4690 case glslang::EOpMod:
4691 case glslang::EOpModAssign:
4692 if (isFloat)
4693 binOp = spv::OpFMod;
4694 else if (isUnsigned)
4695 binOp = spv::OpUMod;
4696 else
4697 binOp = spv::OpSMod;
4698 break;
4699 case glslang::EOpRightShift:
4700 case glslang::EOpRightShiftAssign:
4701 if (isUnsigned)
4702 binOp = spv::OpShiftRightLogical;
4703 else
4704 binOp = spv::OpShiftRightArithmetic;
4705 break;
4706 case glslang::EOpLeftShift:
4707 case glslang::EOpLeftShiftAssign:
4708 binOp = spv::OpShiftLeftLogical;
4709 break;
4710 case glslang::EOpAnd:
4711 case glslang::EOpAndAssign:
4712 binOp = spv::OpBitwiseAnd;
4713 break;
4714 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004715 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004716 binOp = spv::OpLogicalAnd;
4717 break;
4718 case glslang::EOpInclusiveOr:
4719 case glslang::EOpInclusiveOrAssign:
4720 binOp = spv::OpBitwiseOr;
4721 break;
4722 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004723 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004724 binOp = spv::OpLogicalOr;
4725 break;
4726 case glslang::EOpExclusiveOr:
4727 case glslang::EOpExclusiveOrAssign:
4728 binOp = spv::OpBitwiseXor;
4729 break;
4730 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004731 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004732 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004733 break;
4734
4735 case glslang::EOpLessThan:
4736 case glslang::EOpGreaterThan:
4737 case glslang::EOpLessThanEqual:
4738 case glslang::EOpGreaterThanEqual:
4739 case glslang::EOpEqual:
4740 case glslang::EOpNotEqual:
4741 case glslang::EOpVectorEqual:
4742 case glslang::EOpVectorNotEqual:
4743 comparison = true;
4744 break;
4745 default:
4746 break;
4747 }
4748
John Kessenich7c1aa102015-10-15 13:29:11 -06004749 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004750 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004751 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004752 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004753 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004754
4755 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004756 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004757 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004758
qining25262b32016-05-06 17:25:16 -04004759 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004760 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004761 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004762 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004763 }
4764
4765 if (! comparison)
4766 return 0;
4767
John Kessenich7c1aa102015-10-15 13:29:11 -06004768 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004769
John Kessenich4583b612016-08-07 19:14:22 -06004770 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004771 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4772 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004773 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004774 return result;
4775 }
John Kessenich140f3df2015-06-26 16:58:36 -06004776
4777 switch (op) {
4778 case glslang::EOpLessThan:
4779 if (isFloat)
4780 binOp = spv::OpFOrdLessThan;
4781 else if (isUnsigned)
4782 binOp = spv::OpULessThan;
4783 else
4784 binOp = spv::OpSLessThan;
4785 break;
4786 case glslang::EOpGreaterThan:
4787 if (isFloat)
4788 binOp = spv::OpFOrdGreaterThan;
4789 else if (isUnsigned)
4790 binOp = spv::OpUGreaterThan;
4791 else
4792 binOp = spv::OpSGreaterThan;
4793 break;
4794 case glslang::EOpLessThanEqual:
4795 if (isFloat)
4796 binOp = spv::OpFOrdLessThanEqual;
4797 else if (isUnsigned)
4798 binOp = spv::OpULessThanEqual;
4799 else
4800 binOp = spv::OpSLessThanEqual;
4801 break;
4802 case glslang::EOpGreaterThanEqual:
4803 if (isFloat)
4804 binOp = spv::OpFOrdGreaterThanEqual;
4805 else if (isUnsigned)
4806 binOp = spv::OpUGreaterThanEqual;
4807 else
4808 binOp = spv::OpSGreaterThanEqual;
4809 break;
4810 case glslang::EOpEqual:
4811 case glslang::EOpVectorEqual:
4812 if (isFloat)
4813 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004814 else if (isBool)
4815 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004816 else
4817 binOp = spv::OpIEqual;
4818 break;
4819 case glslang::EOpNotEqual:
4820 case glslang::EOpVectorNotEqual:
4821 if (isFloat)
4822 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004823 else if (isBool)
4824 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004825 else
4826 binOp = spv::OpINotEqual;
4827 break;
4828 default:
4829 break;
4830 }
4831
qining25262b32016-05-06 17:25:16 -04004832 if (binOp != spv::OpNop) {
4833 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004834 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004835 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004836 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004837 }
John Kessenich140f3df2015-06-26 16:58:36 -06004838
4839 return 0;
4840}
4841
John Kessenich04bb8a02015-12-12 12:28:14 -07004842//
4843// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4844// These can be any of:
4845//
4846// matrix * scalar
4847// scalar * matrix
4848// matrix * matrix linear algebraic
4849// matrix * vector
4850// vector * matrix
4851// matrix * matrix componentwise
4852// matrix op matrix op in {+, -, /}
4853// matrix op scalar op in {+, -, /}
4854// scalar op matrix op in {+, -, /}
4855//
John Kessenichead86222018-03-28 18:01:20 -06004856spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4857 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004858{
4859 bool firstClass = true;
4860
4861 // First, handle first-class matrix operations (* and matrix/scalar)
4862 switch (op) {
4863 case spv::OpFDiv:
4864 if (builder.isMatrix(left) && builder.isScalar(right)) {
4865 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004866 spv::Id resultType = builder.getTypeId(right);
4867 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004868 op = spv::OpMatrixTimesScalar;
4869 } else
4870 firstClass = false;
4871 break;
4872 case spv::OpMatrixTimesScalar:
4873 if (builder.isMatrix(right))
4874 std::swap(left, right);
4875 assert(builder.isScalar(right));
4876 break;
4877 case spv::OpVectorTimesMatrix:
4878 assert(builder.isVector(left));
4879 assert(builder.isMatrix(right));
4880 break;
4881 case spv::OpMatrixTimesVector:
4882 assert(builder.isMatrix(left));
4883 assert(builder.isVector(right));
4884 break;
4885 case spv::OpMatrixTimesMatrix:
4886 assert(builder.isMatrix(left));
4887 assert(builder.isMatrix(right));
4888 break;
4889 default:
4890 firstClass = false;
4891 break;
4892 }
4893
qining25262b32016-05-06 17:25:16 -04004894 if (firstClass) {
4895 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004896 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004897 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004898 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004899 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004900
LoopDawg592860c2016-06-09 08:57:35 -06004901 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004902 // The result type of all of them is the same type as the (a) matrix operand.
4903 // The algorithm is to:
4904 // - break the matrix(es) into vectors
4905 // - smear any scalar to a vector
4906 // - do vector operations
4907 // - make a matrix out the vector results
4908 switch (op) {
4909 case spv::OpFAdd:
4910 case spv::OpFSub:
4911 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004912 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004913 case spv::OpFMul:
4914 {
4915 // one time set up...
4916 bool leftMat = builder.isMatrix(left);
4917 bool rightMat = builder.isMatrix(right);
4918 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4919 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4920 spv::Id scalarType = builder.getScalarTypeId(typeId);
4921 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4922 std::vector<spv::Id> results;
4923 spv::Id smearVec = spv::NoResult;
4924 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004925 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004926 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004927 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004928
4929 // do each vector op
4930 for (unsigned int c = 0; c < numCols; ++c) {
4931 std::vector<unsigned int> indexes;
4932 indexes.push_back(c);
4933 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4934 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004935 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004936 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004937 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004938 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004939 }
4940
4941 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004942 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004943 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004944 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004945 }
4946 default:
4947 assert(0);
4948 return spv::NoResult;
4949 }
4950}
4951
John Kessenichead86222018-03-28 18:01:20 -06004952spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4953 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004954{
4955 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004956 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004957 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004958 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4959 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004960
4961 switch (op) {
4962 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004963 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004964 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004965 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004966 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004967 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004968 unaryOp = spv::OpSNegate;
4969 break;
4970
4971 case glslang::EOpLogicalNot:
4972 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004973 unaryOp = spv::OpLogicalNot;
4974 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004975 case glslang::EOpBitwiseNot:
4976 unaryOp = spv::OpNot;
4977 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004978
John Kessenich140f3df2015-06-26 16:58:36 -06004979 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004980 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004981 break;
4982 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004983 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004984 break;
4985 case glslang::EOpTranspose:
4986 unaryOp = spv::OpTranspose;
4987 break;
4988
4989 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004996 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004997 break;
4998 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004999 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
5004 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005005 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005006 break;
5007 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005008 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005009 break;
5010 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005011 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005012 break;
5013
5014 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005016 break;
5017 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005018 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005019 break;
5020 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005022 break;
5023 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005024 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005025 break;
5026 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005027 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005028 break;
5029 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005030 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005031 break;
5032
5033 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005034 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005035 break;
5036 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005037 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005038 break;
5039
5040 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005041 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 break;
5043 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005044 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005045 break;
5046 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005047 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005048 break;
5049 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005050 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005051 break;
5052 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005053 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005054 break;
5055 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005056 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005057 break;
5058
5059 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005060 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005061 break;
5062 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005063 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005064 break;
5065 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005066 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005067 break;
5068 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005069 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005070 break;
5071 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005072 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005073 break;
5074 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005075 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005076 break;
5077
5078 case glslang::EOpIsNan:
5079 unaryOp = spv::OpIsNan;
5080 break;
5081 case glslang::EOpIsInf:
5082 unaryOp = spv::OpIsInf;
5083 break;
LoopDawg592860c2016-06-09 08:57:35 -06005084 case glslang::EOpIsFinite:
5085 unaryOp = spv::OpIsFinite;
5086 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005087
Rex Xucbc426e2015-12-15 16:03:10 +08005088 case glslang::EOpFloatBitsToInt:
5089 case glslang::EOpFloatBitsToUint:
5090 case glslang::EOpIntBitsToFloat:
5091 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005092 case glslang::EOpDoubleBitsToInt64:
5093 case glslang::EOpDoubleBitsToUint64:
5094 case glslang::EOpInt64BitsToDouble:
5095 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005096 case glslang::EOpFloat16BitsToInt16:
5097 case glslang::EOpFloat16BitsToUint16:
5098 case glslang::EOpInt16BitsToFloat16:
5099 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005100 unaryOp = spv::OpBitcast;
5101 break;
5102
John Kessenich140f3df2015-06-26 16:58:36 -06005103 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005104 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005107 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005108 break;
5109 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005110 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005111 break;
5112 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005113 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005114 break;
5115 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005116 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005117 break;
5118 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005119 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005120 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005121 case glslang::EOpPackSnorm4x8:
5122 libCall = spv::GLSLstd450PackSnorm4x8;
5123 break;
5124 case glslang::EOpUnpackSnorm4x8:
5125 libCall = spv::GLSLstd450UnpackSnorm4x8;
5126 break;
5127 case glslang::EOpPackUnorm4x8:
5128 libCall = spv::GLSLstd450PackUnorm4x8;
5129 break;
5130 case glslang::EOpUnpackUnorm4x8:
5131 libCall = spv::GLSLstd450UnpackUnorm4x8;
5132 break;
5133 case glslang::EOpPackDouble2x32:
5134 libCall = spv::GLSLstd450PackDouble2x32;
5135 break;
5136 case glslang::EOpUnpackDouble2x32:
5137 libCall = spv::GLSLstd450UnpackDouble2x32;
5138 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005139
Rex Xu8ff43de2016-04-22 16:51:45 +08005140 case glslang::EOpPackInt2x32:
5141 case glslang::EOpUnpackInt2x32:
5142 case glslang::EOpPackUint2x32:
5143 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005144 case glslang::EOpPack16:
5145 case glslang::EOpPack32:
5146 case glslang::EOpPack64:
5147 case glslang::EOpUnpack32:
5148 case glslang::EOpUnpack16:
5149 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005150 case glslang::EOpPackInt2x16:
5151 case glslang::EOpUnpackInt2x16:
5152 case glslang::EOpPackUint2x16:
5153 case glslang::EOpUnpackUint2x16:
5154 case glslang::EOpPackInt4x16:
5155 case glslang::EOpUnpackInt4x16:
5156 case glslang::EOpPackUint4x16:
5157 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005158 case glslang::EOpPackFloat2x16:
5159 case glslang::EOpUnpackFloat2x16:
5160 unaryOp = spv::OpBitcast;
5161 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005162
John Kessenich140f3df2015-06-26 16:58:36 -06005163 case glslang::EOpDPdx:
5164 unaryOp = spv::OpDPdx;
5165 break;
5166 case glslang::EOpDPdy:
5167 unaryOp = spv::OpDPdy;
5168 break;
5169 case glslang::EOpFwidth:
5170 unaryOp = spv::OpFwidth;
5171 break;
5172 case glslang::EOpDPdxFine:
5173 unaryOp = spv::OpDPdxFine;
5174 break;
5175 case glslang::EOpDPdyFine:
5176 unaryOp = spv::OpDPdyFine;
5177 break;
5178 case glslang::EOpFwidthFine:
5179 unaryOp = spv::OpFwidthFine;
5180 break;
5181 case glslang::EOpDPdxCoarse:
5182 unaryOp = spv::OpDPdxCoarse;
5183 break;
5184 case glslang::EOpDPdyCoarse:
5185 unaryOp = spv::OpDPdyCoarse;
5186 break;
5187 case glslang::EOpFwidthCoarse:
5188 unaryOp = spv::OpFwidthCoarse;
5189 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005190 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005191#ifdef AMD_EXTENSIONS
5192 if (typeProxy == glslang::EbtFloat16)
5193 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5194#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005195 libCall = spv::GLSLstd450InterpolateAtCentroid;
5196 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005197 case glslang::EOpAny:
5198 unaryOp = spv::OpAny;
5199 break;
5200 case glslang::EOpAll:
5201 unaryOp = spv::OpAll;
5202 break;
5203
5204 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005205 if (isFloat)
5206 libCall = spv::GLSLstd450FAbs;
5207 else
5208 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005209 break;
5210 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005211 if (isFloat)
5212 libCall = spv::GLSLstd450FSign;
5213 else
5214 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005215 break;
5216
John Kessenichfc51d282015-08-19 13:34:18 -06005217 case glslang::EOpAtomicCounterIncrement:
5218 case glslang::EOpAtomicCounterDecrement:
5219 case glslang::EOpAtomicCounter:
5220 {
5221 // Handle all of the atomics in one place, in createAtomicOperation()
5222 std::vector<spv::Id> operands;
5223 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005224 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005225 }
5226
John Kessenichfc51d282015-08-19 13:34:18 -06005227 case glslang::EOpBitFieldReverse:
5228 unaryOp = spv::OpBitReverse;
5229 break;
5230 case glslang::EOpBitCount:
5231 unaryOp = spv::OpBitCount;
5232 break;
5233 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005234 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005235 break;
5236 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005237 if (isUnsigned)
5238 libCall = spv::GLSLstd450FindUMsb;
5239 else
5240 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005241 break;
5242
Rex Xu574ab042016-04-14 16:53:07 +08005243 case glslang::EOpBallot:
5244 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005245 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005246 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005247 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005248#ifdef AMD_EXTENSIONS
5249 case glslang::EOpMinInvocations:
5250 case glslang::EOpMaxInvocations:
5251 case glslang::EOpAddInvocations:
5252 case glslang::EOpMinInvocationsNonUniform:
5253 case glslang::EOpMaxInvocationsNonUniform:
5254 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005255 case glslang::EOpMinInvocationsInclusiveScan:
5256 case glslang::EOpMaxInvocationsInclusiveScan:
5257 case glslang::EOpAddInvocationsInclusiveScan:
5258 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5259 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5260 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5261 case glslang::EOpMinInvocationsExclusiveScan:
5262 case glslang::EOpMaxInvocationsExclusiveScan:
5263 case glslang::EOpAddInvocationsExclusiveScan:
5264 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5265 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5266 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005267#endif
Rex Xu51596642016-09-21 18:56:12 +08005268 {
5269 std::vector<spv::Id> operands;
5270 operands.push_back(operand);
5271 return createInvocationsOperation(op, typeId, operands, typeProxy);
5272 }
John Kessenich66011cb2018-03-06 16:12:04 -07005273 case glslang::EOpSubgroupAll:
5274 case glslang::EOpSubgroupAny:
5275 case glslang::EOpSubgroupAllEqual:
5276 case glslang::EOpSubgroupBroadcastFirst:
5277 case glslang::EOpSubgroupBallot:
5278 case glslang::EOpSubgroupInverseBallot:
5279 case glslang::EOpSubgroupBallotBitCount:
5280 case glslang::EOpSubgroupBallotInclusiveBitCount:
5281 case glslang::EOpSubgroupBallotExclusiveBitCount:
5282 case glslang::EOpSubgroupBallotFindLSB:
5283 case glslang::EOpSubgroupBallotFindMSB:
5284 case glslang::EOpSubgroupAdd:
5285 case glslang::EOpSubgroupMul:
5286 case glslang::EOpSubgroupMin:
5287 case glslang::EOpSubgroupMax:
5288 case glslang::EOpSubgroupAnd:
5289 case glslang::EOpSubgroupOr:
5290 case glslang::EOpSubgroupXor:
5291 case glslang::EOpSubgroupInclusiveAdd:
5292 case glslang::EOpSubgroupInclusiveMul:
5293 case glslang::EOpSubgroupInclusiveMin:
5294 case glslang::EOpSubgroupInclusiveMax:
5295 case glslang::EOpSubgroupInclusiveAnd:
5296 case glslang::EOpSubgroupInclusiveOr:
5297 case glslang::EOpSubgroupInclusiveXor:
5298 case glslang::EOpSubgroupExclusiveAdd:
5299 case glslang::EOpSubgroupExclusiveMul:
5300 case glslang::EOpSubgroupExclusiveMin:
5301 case glslang::EOpSubgroupExclusiveMax:
5302 case glslang::EOpSubgroupExclusiveAnd:
5303 case glslang::EOpSubgroupExclusiveOr:
5304 case glslang::EOpSubgroupExclusiveXor:
5305 case glslang::EOpSubgroupQuadSwapHorizontal:
5306 case glslang::EOpSubgroupQuadSwapVertical:
5307 case glslang::EOpSubgroupQuadSwapDiagonal: {
5308 std::vector<spv::Id> operands;
5309 operands.push_back(operand);
5310 return createSubgroupOperation(op, typeId, operands, typeProxy);
5311 }
Rex Xu9d93a232016-05-05 12:30:44 +08005312#ifdef AMD_EXTENSIONS
5313 case glslang::EOpMbcnt:
5314 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5315 libCall = spv::MbcntAMD;
5316 break;
5317
5318 case glslang::EOpCubeFaceIndex:
5319 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5320 libCall = spv::CubeFaceIndexAMD;
5321 break;
5322
5323 case glslang::EOpCubeFaceCoord:
5324 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5325 libCall = spv::CubeFaceCoordAMD;
5326 break;
5327#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005328#ifdef NV_EXTENSIONS
5329 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005330 unaryOp = spv::OpGroupNonUniformPartitionNV;
5331 break;
5332#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005333 default:
5334 return 0;
5335 }
5336
5337 spv::Id id;
5338 if (libCall >= 0) {
5339 std::vector<spv::Id> args;
5340 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005341 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005342 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005343 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005344 }
John Kessenich140f3df2015-06-26 16:58:36 -06005345
John Kessenichead86222018-03-28 18:01:20 -06005346 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005347 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005348 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005349}
5350
John Kessenich7a53f762016-01-20 11:19:27 -07005351// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005352spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5353 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005354{
5355 // Handle unary operations vector by vector.
5356 // The result type is the same type as the original type.
5357 // The algorithm is to:
5358 // - break the matrix into vectors
5359 // - apply the operation to each vector
5360 // - make a matrix out the vector results
5361
5362 // get the types sorted out
5363 int numCols = builder.getNumColumns(operand);
5364 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005365 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5366 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005367 std::vector<spv::Id> results;
5368
5369 // do each vector op
5370 for (int c = 0; c < numCols; ++c) {
5371 std::vector<unsigned int> indexes;
5372 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005373 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5374 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005375 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005376 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005377 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005378 }
5379
5380 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005381 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005382 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005383 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005384}
5385
John Kessenichad7645f2018-06-04 19:11:25 -06005386// For converting integers where both the bitwidth and the signedness could
5387// change, but only do the width change here. The caller is still responsible
5388// for the signedness conversion.
5389spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005390{
John Kessenichad7645f2018-06-04 19:11:25 -06005391 // Get the result type width, based on the type to convert to.
5392 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005393 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005394 case glslang::EOpConvInt16ToUint8:
5395 case glslang::EOpConvIntToUint8:
5396 case glslang::EOpConvInt64ToUint8:
5397 case glslang::EOpConvUint16ToInt8:
5398 case glslang::EOpConvUintToInt8:
5399 case glslang::EOpConvUint64ToInt8:
5400 width = 8;
5401 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005402 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005403 case glslang::EOpConvIntToUint16:
5404 case glslang::EOpConvInt64ToUint16:
5405 case glslang::EOpConvUint8ToInt16:
5406 case glslang::EOpConvUintToInt16:
5407 case glslang::EOpConvUint64ToInt16:
5408 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005409 break;
5410 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005411 case glslang::EOpConvInt16ToUint:
5412 case glslang::EOpConvInt64ToUint:
5413 case glslang::EOpConvUint8ToInt:
5414 case glslang::EOpConvUint16ToInt:
5415 case glslang::EOpConvUint64ToInt:
5416 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005417 break;
5418 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005419 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005420 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005421 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005422 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005423 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005424 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005425 break;
5426
5427 default:
5428 assert(false && "Default missing");
5429 break;
5430 }
5431
John Kessenichad7645f2018-06-04 19:11:25 -06005432 // Get the conversion operation and result type,
5433 // based on the target width, but the source type.
5434 spv::Id type = spv::NoType;
5435 spv::Op convOp = spv::OpNop;
5436 switch(op) {
5437 case glslang::EOpConvInt8ToUint16:
5438 case glslang::EOpConvInt8ToUint:
5439 case glslang::EOpConvInt8ToUint64:
5440 case glslang::EOpConvInt16ToUint8:
5441 case glslang::EOpConvInt16ToUint:
5442 case glslang::EOpConvInt16ToUint64:
5443 case glslang::EOpConvIntToUint8:
5444 case glslang::EOpConvIntToUint16:
5445 case glslang::EOpConvIntToUint64:
5446 case glslang::EOpConvInt64ToUint8:
5447 case glslang::EOpConvInt64ToUint16:
5448 case glslang::EOpConvInt64ToUint:
5449 convOp = spv::OpSConvert;
5450 type = builder.makeIntType(width);
5451 break;
5452 default:
5453 convOp = spv::OpUConvert;
5454 type = builder.makeUintType(width);
5455 break;
5456 }
5457
John Kessenich66011cb2018-03-06 16:12:04 -07005458 if (vectorSize > 0)
5459 type = builder.makeVectorType(type, vectorSize);
5460
John Kessenichad7645f2018-06-04 19:11:25 -06005461 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005462}
5463
John Kessenichead86222018-03-28 18:01:20 -06005464spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5465 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005466{
5467 spv::Op convOp = spv::OpNop;
5468 spv::Id zero = 0;
5469 spv::Id one = 0;
5470
5471 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5472
5473 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005474 case glslang::EOpConvInt8ToBool:
5475 case glslang::EOpConvUint8ToBool:
5476 zero = builder.makeUint8Constant(0);
5477 zero = makeSmearedConstant(zero, vectorSize);
5478 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005479 case glslang::EOpConvInt16ToBool:
5480 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005481 zero = builder.makeUint16Constant(0);
5482 zero = makeSmearedConstant(zero, vectorSize);
5483 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5484 case glslang::EOpConvIntToBool:
5485 case glslang::EOpConvUintToBool:
5486 zero = builder.makeUintConstant(0);
5487 zero = makeSmearedConstant(zero, vectorSize);
5488 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5489 case glslang::EOpConvInt64ToBool:
5490 case glslang::EOpConvUint64ToBool:
5491 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005492 zero = makeSmearedConstant(zero, vectorSize);
5493 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5494
5495 case glslang::EOpConvFloatToBool:
5496 zero = builder.makeFloatConstant(0.0F);
5497 zero = makeSmearedConstant(zero, vectorSize);
5498 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5499
5500 case glslang::EOpConvDoubleToBool:
5501 zero = builder.makeDoubleConstant(0.0);
5502 zero = makeSmearedConstant(zero, vectorSize);
5503 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5504
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005505 case glslang::EOpConvFloat16ToBool:
5506 zero = builder.makeFloat16Constant(0.0F);
5507 zero = makeSmearedConstant(zero, vectorSize);
5508 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005509
John Kessenich140f3df2015-06-26 16:58:36 -06005510 case glslang::EOpConvBoolToFloat:
5511 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005512 zero = builder.makeFloatConstant(0.0F);
5513 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005515
John Kessenich140f3df2015-06-26 16:58:36 -06005516 case glslang::EOpConvBoolToDouble:
5517 convOp = spv::OpSelect;
5518 zero = builder.makeDoubleConstant(0.0);
5519 one = builder.makeDoubleConstant(1.0);
5520 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005521
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005522 case glslang::EOpConvBoolToFloat16:
5523 convOp = spv::OpSelect;
5524 zero = builder.makeFloat16Constant(0.0F);
5525 one = builder.makeFloat16Constant(1.0F);
5526 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005527
5528 case glslang::EOpConvBoolToInt8:
5529 zero = builder.makeInt8Constant(0);
5530 one = builder.makeInt8Constant(1);
5531 convOp = spv::OpSelect;
5532 break;
5533
5534 case glslang::EOpConvBoolToUint8:
5535 zero = builder.makeUint8Constant(0);
5536 one = builder.makeUint8Constant(1);
5537 convOp = spv::OpSelect;
5538 break;
5539
5540 case glslang::EOpConvBoolToInt16:
5541 zero = builder.makeInt16Constant(0);
5542 one = builder.makeInt16Constant(1);
5543 convOp = spv::OpSelect;
5544 break;
5545
5546 case glslang::EOpConvBoolToUint16:
5547 zero = builder.makeUint16Constant(0);
5548 one = builder.makeUint16Constant(1);
5549 convOp = spv::OpSelect;
5550 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005551
John Kessenich140f3df2015-06-26 16:58:36 -06005552 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005553 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005554 if (op == glslang::EOpConvBoolToInt64)
5555 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005556 else
5557 zero = builder.makeIntConstant(0);
5558
5559 if (op == glslang::EOpConvBoolToInt64)
5560 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005561 else
5562 one = builder.makeIntConstant(1);
5563
John Kessenich140f3df2015-06-26 16:58:36 -06005564 convOp = spv::OpSelect;
5565 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005566
John Kessenich140f3df2015-06-26 16:58:36 -06005567 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005568 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005569 if (op == glslang::EOpConvBoolToUint64)
5570 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005571 else
5572 zero = builder.makeUintConstant(0);
5573
5574 if (op == glslang::EOpConvBoolToUint64)
5575 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005576 else
5577 one = builder.makeUintConstant(1);
5578
John Kessenich140f3df2015-06-26 16:58:36 -06005579 convOp = spv::OpSelect;
5580 break;
5581
John Kessenich66011cb2018-03-06 16:12:04 -07005582 case glslang::EOpConvInt8ToFloat16:
5583 case glslang::EOpConvInt8ToFloat:
5584 case glslang::EOpConvInt8ToDouble:
5585 case glslang::EOpConvInt16ToFloat16:
5586 case glslang::EOpConvInt16ToFloat:
5587 case glslang::EOpConvInt16ToDouble:
5588 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005589 case glslang::EOpConvIntToFloat:
5590 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005591 case glslang::EOpConvInt64ToFloat:
5592 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005593 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005594 convOp = spv::OpConvertSToF;
5595 break;
5596
John Kessenich66011cb2018-03-06 16:12:04 -07005597 case glslang::EOpConvUint8ToFloat16:
5598 case glslang::EOpConvUint8ToFloat:
5599 case glslang::EOpConvUint8ToDouble:
5600 case glslang::EOpConvUint16ToFloat16:
5601 case glslang::EOpConvUint16ToFloat:
5602 case glslang::EOpConvUint16ToDouble:
5603 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005604 case glslang::EOpConvUintToFloat:
5605 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005606 case glslang::EOpConvUint64ToFloat:
5607 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005608 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005609 convOp = spv::OpConvertUToF;
5610 break;
5611
5612 case glslang::EOpConvDoubleToFloat:
5613 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005614 case glslang::EOpConvDoubleToFloat16:
5615 case glslang::EOpConvFloat16ToDouble:
5616 case glslang::EOpConvFloatToFloat16:
5617 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005618 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005619 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005620 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005621 break;
5622
John Kessenich66011cb2018-03-06 16:12:04 -07005623 case glslang::EOpConvFloat16ToInt8:
5624 case glslang::EOpConvFloatToInt8:
5625 case glslang::EOpConvDoubleToInt8:
5626 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005627 case glslang::EOpConvFloatToInt16:
5628 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005629 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005630 case glslang::EOpConvFloatToInt:
5631 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005632 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005633 case glslang::EOpConvFloatToInt64:
5634 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005635 convOp = spv::OpConvertFToS;
5636 break;
5637
John Kessenich66011cb2018-03-06 16:12:04 -07005638 case glslang::EOpConvUint8ToInt8:
5639 case glslang::EOpConvInt8ToUint8:
5640 case glslang::EOpConvUint16ToInt16:
5641 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005642 case glslang::EOpConvUintToInt:
5643 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005644 case glslang::EOpConvUint64ToInt64:
5645 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005646 if (builder.isInSpecConstCodeGenMode()) {
5647 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005648 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5649 zero = builder.makeUint8Constant(0);
5650 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005651 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005652 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5653 zero = builder.makeUint64Constant(0);
5654 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005655 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005656 }
qining189b2032016-04-12 23:16:20 -04005657 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005658 // Use OpIAdd, instead of OpBitcast to do the conversion when
5659 // generating for OpSpecConstantOp instruction.
5660 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5661 }
5662 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005663 convOp = spv::OpBitcast;
5664 break;
5665
John Kessenich66011cb2018-03-06 16:12:04 -07005666 case glslang::EOpConvFloat16ToUint8:
5667 case glslang::EOpConvFloatToUint8:
5668 case glslang::EOpConvDoubleToUint8:
5669 case glslang::EOpConvFloat16ToUint16:
5670 case glslang::EOpConvFloatToUint16:
5671 case glslang::EOpConvDoubleToUint16:
5672 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005673 case glslang::EOpConvFloatToUint:
5674 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005675 case glslang::EOpConvFloatToUint64:
5676 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005677 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005678 convOp = spv::OpConvertFToU;
5679 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005680
John Kessenich66011cb2018-03-06 16:12:04 -07005681 case glslang::EOpConvInt8ToInt16:
5682 case glslang::EOpConvInt8ToInt:
5683 case glslang::EOpConvInt8ToInt64:
5684 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005685 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005686 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005687 case glslang::EOpConvIntToInt8:
5688 case glslang::EOpConvIntToInt16:
5689 case glslang::EOpConvIntToInt64:
5690 case glslang::EOpConvInt64ToInt8:
5691 case glslang::EOpConvInt64ToInt16:
5692 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005693 convOp = spv::OpSConvert;
5694 break;
5695
John Kessenich66011cb2018-03-06 16:12:04 -07005696 case glslang::EOpConvUint8ToUint16:
5697 case glslang::EOpConvUint8ToUint:
5698 case glslang::EOpConvUint8ToUint64:
5699 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005700 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005701 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005702 case glslang::EOpConvUintToUint8:
5703 case glslang::EOpConvUintToUint16:
5704 case glslang::EOpConvUintToUint64:
5705 case glslang::EOpConvUint64ToUint8:
5706 case glslang::EOpConvUint64ToUint16:
5707 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005708 convOp = spv::OpUConvert;
5709 break;
5710
John Kessenich66011cb2018-03-06 16:12:04 -07005711 case glslang::EOpConvInt8ToUint16:
5712 case glslang::EOpConvInt8ToUint:
5713 case glslang::EOpConvInt8ToUint64:
5714 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005715 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005716 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005717 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005718 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005719 case glslang::EOpConvIntToUint64:
5720 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005721 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005722 case glslang::EOpConvInt64ToUint:
5723 case glslang::EOpConvUint8ToInt16:
5724 case glslang::EOpConvUint8ToInt:
5725 case glslang::EOpConvUint8ToInt64:
5726 case glslang::EOpConvUint16ToInt8:
5727 case glslang::EOpConvUint16ToInt:
5728 case glslang::EOpConvUint16ToInt64:
5729 case glslang::EOpConvUintToInt8:
5730 case glslang::EOpConvUintToInt16:
5731 case glslang::EOpConvUintToInt64:
5732 case glslang::EOpConvUint64ToInt8:
5733 case glslang::EOpConvUint64ToInt16:
5734 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005735 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005736 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005737
5738 if (builder.isInSpecConstCodeGenMode()) {
5739 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005740 switch(op) {
5741 case glslang::EOpConvInt16ToUint8:
5742 case glslang::EOpConvIntToUint8:
5743 case glslang::EOpConvInt64ToUint8:
5744 case glslang::EOpConvUint16ToInt8:
5745 case glslang::EOpConvUintToInt8:
5746 case glslang::EOpConvUint64ToInt8:
5747 zero = builder.makeUint8Constant(0);
5748 break;
5749 case glslang::EOpConvInt8ToUint16:
5750 case glslang::EOpConvIntToUint16:
5751 case glslang::EOpConvInt64ToUint16:
5752 case glslang::EOpConvUint8ToInt16:
5753 case glslang::EOpConvUintToInt16:
5754 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005755 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005756 break;
5757 case glslang::EOpConvInt8ToUint:
5758 case glslang::EOpConvInt16ToUint:
5759 case glslang::EOpConvInt64ToUint:
5760 case glslang::EOpConvUint8ToInt:
5761 case glslang::EOpConvUint16ToInt:
5762 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005763 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005764 break;
5765 case glslang::EOpConvInt8ToUint64:
5766 case glslang::EOpConvInt16ToUint64:
5767 case glslang::EOpConvIntToUint64:
5768 case glslang::EOpConvUint8ToInt64:
5769 case glslang::EOpConvUint16ToInt64:
5770 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005771 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005772 break;
5773 default:
5774 assert(false && "Default missing");
5775 break;
5776 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005777 zero = makeSmearedConstant(zero, vectorSize);
5778 // Use OpIAdd, instead of OpBitcast to do the conversion when
5779 // generating for OpSpecConstantOp instruction.
5780 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5781 }
5782 // For normal run-time conversion instruction, use OpBitcast.
5783 convOp = spv::OpBitcast;
5784 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005785 default:
5786 break;
5787 }
5788
5789 spv::Id result = 0;
5790 if (convOp == spv::OpNop)
5791 return result;
5792
5793 if (convOp == spv::OpSelect) {
5794 zero = makeSmearedConstant(zero, vectorSize);
5795 one = makeSmearedConstant(one, vectorSize);
5796 result = builder.createTriOp(convOp, destType, operand, one, zero);
5797 } else
5798 result = builder.createUnaryOp(convOp, destType, operand);
5799
John Kessenichead86222018-03-28 18:01:20 -06005800 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005801 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005802 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005803}
5804
5805spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5806{
5807 if (vectorSize == 0)
5808 return constant;
5809
5810 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5811 std::vector<spv::Id> components;
5812 for (int c = 0; c < vectorSize; ++c)
5813 components.push_back(constant);
5814 return builder.makeCompositeConstant(vectorTypeId, components);
5815}
5816
John Kessenich426394d2015-07-23 10:22:48 -06005817// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005818spv::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 -06005819{
5820 spv::Op opCode = spv::OpNop;
5821
5822 switch (op) {
5823 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005824 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005825 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005826 opCode = spv::OpAtomicIAdd;
5827 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005828 case glslang::EOpAtomicCounterSubtract:
5829 opCode = spv::OpAtomicISub;
5830 break;
John Kessenich426394d2015-07-23 10:22:48 -06005831 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005832 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005833 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005834 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005835 break;
5836 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005837 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005838 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005839 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005840 break;
5841 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005842 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005843 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005844 opCode = spv::OpAtomicAnd;
5845 break;
5846 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005847 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005848 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005849 opCode = spv::OpAtomicOr;
5850 break;
5851 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005852 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005853 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005854 opCode = spv::OpAtomicXor;
5855 break;
5856 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005857 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005858 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005859 opCode = spv::OpAtomicExchange;
5860 break;
5861 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005862 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005863 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005864 opCode = spv::OpAtomicCompareExchange;
5865 break;
5866 case glslang::EOpAtomicCounterIncrement:
5867 opCode = spv::OpAtomicIIncrement;
5868 break;
5869 case glslang::EOpAtomicCounterDecrement:
5870 opCode = spv::OpAtomicIDecrement;
5871 break;
5872 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005873 case glslang::EOpImageAtomicLoad:
5874 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005875 opCode = spv::OpAtomicLoad;
5876 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005877 case glslang::EOpAtomicStore:
5878 case glslang::EOpImageAtomicStore:
5879 opCode = spv::OpAtomicStore;
5880 break;
John Kessenich426394d2015-07-23 10:22:48 -06005881 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005882 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005883 break;
5884 }
5885
Rex Xue8fe8b02017-09-26 15:42:56 +08005886 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5887 builder.addCapability(spv::CapabilityInt64Atomics);
5888
John Kessenich426394d2015-07-23 10:22:48 -06005889 // Sort out the operands
5890 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005891 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005892 // - compare-exchange swaps the value and comparator
5893 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005894 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005895 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5896 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5897 spv::Id scopeId;
5898 if (glslangIntermediate->usingVulkanMemoryModel()) {
5899 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5900 } else {
5901 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5902 }
5903 // semantics default to relaxed
5904 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5905 spv::Id semanticsId2 = semanticsId;
5906
5907 pointerId = operands[0];
5908 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5909 // no additional operands
5910 } else if (opCode == spv::OpAtomicCompareExchange) {
5911 compareId = operands[1];
5912 valueId = operands[2];
5913 if (operands.size() > 3) {
5914 scopeId = operands[3];
5915 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5916 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5917 }
5918 } else if (opCode == spv::OpAtomicLoad) {
5919 if (operands.size() > 1) {
5920 scopeId = operands[1];
5921 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5922 }
5923 } else {
5924 // atomic store or RMW
5925 valueId = operands[1];
5926 if (operands.size() > 2) {
5927 scopeId = operands[2];
5928 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5929 }
Rex Xu04db3f52015-09-16 11:44:02 +08005930 }
John Kessenich426394d2015-07-23 10:22:48 -06005931
Jeff Bolz36831c92018-09-05 10:11:41 -05005932 // Check for capabilities
5933 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5934 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5935 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5936 }
John Kessenich426394d2015-07-23 10:22:48 -06005937
Jeff Bolz36831c92018-09-05 10:11:41 -05005938 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5939 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5940 }
John Kessenich48d6e792017-10-06 21:21:48 -06005941
Jeff Bolz36831c92018-09-05 10:11:41 -05005942 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5943 spvAtomicOperands.push_back(pointerId);
5944 spvAtomicOperands.push_back(scopeId);
5945 spvAtomicOperands.push_back(semanticsId);
5946 if (opCode == spv::OpAtomicCompareExchange) {
5947 spvAtomicOperands.push_back(semanticsId2);
5948 spvAtomicOperands.push_back(valueId);
5949 spvAtomicOperands.push_back(compareId);
5950 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5951 spvAtomicOperands.push_back(valueId);
5952 }
John Kessenich48d6e792017-10-06 21:21:48 -06005953
Jeff Bolz36831c92018-09-05 10:11:41 -05005954 if (opCode == spv::OpAtomicStore) {
5955 builder.createNoResultOp(opCode, spvAtomicOperands);
5956 return 0;
5957 } else {
5958 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5959
5960 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5961 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5962 if (op == glslang::EOpAtomicCounterDecrement)
5963 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5964
5965 return resultId;
5966 }
John Kessenich426394d2015-07-23 10:22:48 -06005967}
5968
John Kessenich91cef522016-05-05 16:45:40 -06005969// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005970spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005971{
Corentin Walleze7061422018-08-08 15:20:15 +02005972#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005973 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5974 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005975#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005976
Rex Xu51596642016-09-21 18:56:12 +08005977 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005978 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005979 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5980
chaocf200da82016-12-20 12:44:35 -08005981 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5982 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005983 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5984 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005985 } else if (op == glslang::EOpAnyInvocation ||
5986 op == glslang::EOpAllInvocations ||
5987 op == glslang::EOpAllInvocationsEqual) {
5988 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5989 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005990 } else {
5991 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005992#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005993 if (op == glslang::EOpMinInvocationsNonUniform ||
5994 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005995 op == glslang::EOpAddInvocationsNonUniform ||
5996 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5997 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5998 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5999 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6000 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6001 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006002 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006003#endif
Rex Xu51596642016-09-21 18:56:12 +08006004
Rex Xu9d93a232016-05-05 12:30:44 +08006005#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006006 switch (op) {
6007 case glslang::EOpMinInvocations:
6008 case glslang::EOpMaxInvocations:
6009 case glslang::EOpAddInvocations:
6010 case glslang::EOpMinInvocationsNonUniform:
6011 case glslang::EOpMaxInvocationsNonUniform:
6012 case glslang::EOpAddInvocationsNonUniform:
6013 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006014 break;
6015 case glslang::EOpMinInvocationsInclusiveScan:
6016 case glslang::EOpMaxInvocationsInclusiveScan:
6017 case glslang::EOpAddInvocationsInclusiveScan:
6018 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6019 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6020 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6021 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006022 break;
6023 case glslang::EOpMinInvocationsExclusiveScan:
6024 case glslang::EOpMaxInvocationsExclusiveScan:
6025 case glslang::EOpAddInvocationsExclusiveScan:
6026 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6027 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6028 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6029 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006030 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006031 default:
6032 break;
Rex Xu430ef402016-10-14 17:22:23 +08006033 }
John Kessenich149afc32018-08-14 13:31:43 -06006034 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6035 spvGroupOperands.push_back(scope);
6036 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006037 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006038 spvGroupOperands.push_back(groupOp);
6039 }
Rex Xu9d93a232016-05-05 12:30:44 +08006040#endif
Rex Xu51596642016-09-21 18:56:12 +08006041 }
6042
John Kessenich149afc32018-08-14 13:31:43 -06006043 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6044 spv::IdImmediate op = { true, *opIt };
6045 spvGroupOperands.push_back(op);
6046 }
John Kessenich91cef522016-05-05 16:45:40 -06006047
6048 switch (op) {
6049 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006050 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006051 break;
John Kessenich91cef522016-05-05 16:45:40 -06006052 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006053 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006054 break;
John Kessenich91cef522016-05-05 16:45:40 -06006055 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006056 opCode = spv::OpSubgroupAllEqualKHR;
6057 break;
Rex Xu51596642016-09-21 18:56:12 +08006058 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006059 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006060 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006061 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006062 break;
6063 case glslang::EOpReadFirstInvocation:
6064 opCode = spv::OpSubgroupFirstInvocationKHR;
6065 break;
6066 case glslang::EOpBallot:
6067 {
6068 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6069 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6070 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6071 //
6072 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6073 //
6074 spv::Id uintType = builder.makeUintType(32);
6075 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6076 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6077
6078 std::vector<spv::Id> components;
6079 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6080 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6081
6082 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6083 return builder.createUnaryOp(spv::OpBitcast, typeId,
6084 builder.createCompositeConstruct(uvec2Type, components));
6085 }
6086
Rex Xu9d93a232016-05-05 12:30:44 +08006087#ifdef AMD_EXTENSIONS
6088 case glslang::EOpMinInvocations:
6089 case glslang::EOpMaxInvocations:
6090 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006091 case glslang::EOpMinInvocationsInclusiveScan:
6092 case glslang::EOpMaxInvocationsInclusiveScan:
6093 case glslang::EOpAddInvocationsInclusiveScan:
6094 case glslang::EOpMinInvocationsExclusiveScan:
6095 case glslang::EOpMaxInvocationsExclusiveScan:
6096 case glslang::EOpAddInvocationsExclusiveScan:
6097 if (op == glslang::EOpMinInvocations ||
6098 op == glslang::EOpMinInvocationsInclusiveScan ||
6099 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006100 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006101 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006102 else {
6103 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006104 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006105 else
Rex Xu51596642016-09-21 18:56:12 +08006106 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006107 }
Rex Xu430ef402016-10-14 17:22:23 +08006108 } else if (op == glslang::EOpMaxInvocations ||
6109 op == glslang::EOpMaxInvocationsInclusiveScan ||
6110 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006111 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006112 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006113 else {
6114 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006115 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006116 else
Rex Xu51596642016-09-21 18:56:12 +08006117 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006118 }
6119 } else {
6120 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006121 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006122 else
Rex Xu51596642016-09-21 18:56:12 +08006123 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006124 }
6125
Rex Xu2bbbe062016-08-23 15:41:05 +08006126 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006127 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006128
6129 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006130 case glslang::EOpMinInvocationsNonUniform:
6131 case glslang::EOpMaxInvocationsNonUniform:
6132 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006133 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6134 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6135 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6136 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6137 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6138 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6139 if (op == glslang::EOpMinInvocationsNonUniform ||
6140 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6141 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006142 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006143 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006144 else {
6145 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006146 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006147 else
Rex Xu51596642016-09-21 18:56:12 +08006148 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006149 }
6150 }
Rex Xu430ef402016-10-14 17:22:23 +08006151 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6152 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6153 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006154 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006155 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006156 else {
6157 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006158 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006159 else
Rex Xu51596642016-09-21 18:56:12 +08006160 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006161 }
6162 }
6163 else {
6164 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006165 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006166 else
Rex Xu51596642016-09-21 18:56:12 +08006167 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006168 }
6169
Rex Xu2bbbe062016-08-23 15:41:05 +08006170 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006171 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006172
6173 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006174#endif
John Kessenich91cef522016-05-05 16:45:40 -06006175 default:
6176 logger->missingFunctionality("invocation operation");
6177 return spv::NoResult;
6178 }
Rex Xu51596642016-09-21 18:56:12 +08006179
6180 assert(opCode != spv::OpNop);
6181 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006182}
6183
Rex Xu2bbbe062016-08-23 15:41:05 +08006184// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006185spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6186 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006187{
Rex Xub7072052016-09-26 15:53:40 +08006188#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006189 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6190 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006191 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006192 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006193 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6194 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6195 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006196#else
6197 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6198 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006199 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6200 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006201#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006202
6203 // Handle group invocation operations scalar by scalar.
6204 // The result type is the same type as the original type.
6205 // The algorithm is to:
6206 // - break the vector into scalars
6207 // - apply the operation to each scalar
6208 // - make a vector out the scalar results
6209
6210 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006211 int numComponents = builder.getNumComponents(operands[0]);
6212 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006213 std::vector<spv::Id> results;
6214
6215 // do each scalar op
6216 for (int comp = 0; comp < numComponents; ++comp) {
6217 std::vector<unsigned int> indexes;
6218 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006219 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6220 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006221 if (op == spv::OpSubgroupReadInvocationKHR) {
6222 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006223 spv::IdImmediate operand = { true, operands[1] };
6224 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006225 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006226 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6227 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006228 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006229 spv::IdImmediate operand = { true, operands[1] };
6230 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006231 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006232 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6233 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006234 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006235 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006236 spvGroupOperands.push_back(scalar);
6237 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006238
Rex Xub7072052016-09-26 15:53:40 +08006239 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006240 }
6241
6242 // put the pieces together
6243 return builder.createCompositeConstruct(typeId, results);
6244}
Rex Xu2bbbe062016-08-23 15:41:05 +08006245
John Kessenich66011cb2018-03-06 16:12:04 -07006246// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006247spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6248 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006249{
6250 // Add the required capabilities.
6251 switch (op) {
6252 case glslang::EOpSubgroupElect:
6253 builder.addCapability(spv::CapabilityGroupNonUniform);
6254 break;
6255 case glslang::EOpSubgroupAll:
6256 case glslang::EOpSubgroupAny:
6257 case glslang::EOpSubgroupAllEqual:
6258 builder.addCapability(spv::CapabilityGroupNonUniform);
6259 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6260 break;
6261 case glslang::EOpSubgroupBroadcast:
6262 case glslang::EOpSubgroupBroadcastFirst:
6263 case glslang::EOpSubgroupBallot:
6264 case glslang::EOpSubgroupInverseBallot:
6265 case glslang::EOpSubgroupBallotBitExtract:
6266 case glslang::EOpSubgroupBallotBitCount:
6267 case glslang::EOpSubgroupBallotInclusiveBitCount:
6268 case glslang::EOpSubgroupBallotExclusiveBitCount:
6269 case glslang::EOpSubgroupBallotFindLSB:
6270 case glslang::EOpSubgroupBallotFindMSB:
6271 builder.addCapability(spv::CapabilityGroupNonUniform);
6272 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6273 break;
6274 case glslang::EOpSubgroupShuffle:
6275 case glslang::EOpSubgroupShuffleXor:
6276 builder.addCapability(spv::CapabilityGroupNonUniform);
6277 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6278 break;
6279 case glslang::EOpSubgroupShuffleUp:
6280 case glslang::EOpSubgroupShuffleDown:
6281 builder.addCapability(spv::CapabilityGroupNonUniform);
6282 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6283 break;
6284 case glslang::EOpSubgroupAdd:
6285 case glslang::EOpSubgroupMul:
6286 case glslang::EOpSubgroupMin:
6287 case glslang::EOpSubgroupMax:
6288 case glslang::EOpSubgroupAnd:
6289 case glslang::EOpSubgroupOr:
6290 case glslang::EOpSubgroupXor:
6291 case glslang::EOpSubgroupInclusiveAdd:
6292 case glslang::EOpSubgroupInclusiveMul:
6293 case glslang::EOpSubgroupInclusiveMin:
6294 case glslang::EOpSubgroupInclusiveMax:
6295 case glslang::EOpSubgroupInclusiveAnd:
6296 case glslang::EOpSubgroupInclusiveOr:
6297 case glslang::EOpSubgroupInclusiveXor:
6298 case glslang::EOpSubgroupExclusiveAdd:
6299 case glslang::EOpSubgroupExclusiveMul:
6300 case glslang::EOpSubgroupExclusiveMin:
6301 case glslang::EOpSubgroupExclusiveMax:
6302 case glslang::EOpSubgroupExclusiveAnd:
6303 case glslang::EOpSubgroupExclusiveOr:
6304 case glslang::EOpSubgroupExclusiveXor:
6305 builder.addCapability(spv::CapabilityGroupNonUniform);
6306 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6307 break;
6308 case glslang::EOpSubgroupClusteredAdd:
6309 case glslang::EOpSubgroupClusteredMul:
6310 case glslang::EOpSubgroupClusteredMin:
6311 case glslang::EOpSubgroupClusteredMax:
6312 case glslang::EOpSubgroupClusteredAnd:
6313 case glslang::EOpSubgroupClusteredOr:
6314 case glslang::EOpSubgroupClusteredXor:
6315 builder.addCapability(spv::CapabilityGroupNonUniform);
6316 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6317 break;
6318 case glslang::EOpSubgroupQuadBroadcast:
6319 case glslang::EOpSubgroupQuadSwapHorizontal:
6320 case glslang::EOpSubgroupQuadSwapVertical:
6321 case glslang::EOpSubgroupQuadSwapDiagonal:
6322 builder.addCapability(spv::CapabilityGroupNonUniform);
6323 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6324 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006325#ifdef NV_EXTENSIONS
6326 case glslang::EOpSubgroupPartitionedAdd:
6327 case glslang::EOpSubgroupPartitionedMul:
6328 case glslang::EOpSubgroupPartitionedMin:
6329 case glslang::EOpSubgroupPartitionedMax:
6330 case glslang::EOpSubgroupPartitionedAnd:
6331 case glslang::EOpSubgroupPartitionedOr:
6332 case glslang::EOpSubgroupPartitionedXor:
6333 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6334 case glslang::EOpSubgroupPartitionedInclusiveMul:
6335 case glslang::EOpSubgroupPartitionedInclusiveMin:
6336 case glslang::EOpSubgroupPartitionedInclusiveMax:
6337 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6338 case glslang::EOpSubgroupPartitionedInclusiveOr:
6339 case glslang::EOpSubgroupPartitionedInclusiveXor:
6340 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6341 case glslang::EOpSubgroupPartitionedExclusiveMul:
6342 case glslang::EOpSubgroupPartitionedExclusiveMin:
6343 case glslang::EOpSubgroupPartitionedExclusiveMax:
6344 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6345 case glslang::EOpSubgroupPartitionedExclusiveOr:
6346 case glslang::EOpSubgroupPartitionedExclusiveXor:
6347 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6348 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6349 break;
6350#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006351 default: assert(0 && "Unhandled subgroup operation!");
6352 }
6353
6354 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6355 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6356 const bool isBool = typeProxy == glslang::EbtBool;
6357
6358 spv::Op opCode = spv::OpNop;
6359
6360 // Figure out which opcode to use.
6361 switch (op) {
6362 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6363 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6364 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6365 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6366 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6367 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6368 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6369 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6370 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6371 case glslang::EOpSubgroupBallotBitCount:
6372 case glslang::EOpSubgroupBallotInclusiveBitCount:
6373 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6374 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6375 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6376 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6377 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6378 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6379 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6380 case glslang::EOpSubgroupAdd:
6381 case glslang::EOpSubgroupInclusiveAdd:
6382 case glslang::EOpSubgroupExclusiveAdd:
6383 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006384#ifdef NV_EXTENSIONS
6385 case glslang::EOpSubgroupPartitionedAdd:
6386 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6387 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6388#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006389 if (isFloat) {
6390 opCode = spv::OpGroupNonUniformFAdd;
6391 } else {
6392 opCode = spv::OpGroupNonUniformIAdd;
6393 }
6394 break;
6395 case glslang::EOpSubgroupMul:
6396 case glslang::EOpSubgroupInclusiveMul:
6397 case glslang::EOpSubgroupExclusiveMul:
6398 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006399#ifdef NV_EXTENSIONS
6400 case glslang::EOpSubgroupPartitionedMul:
6401 case glslang::EOpSubgroupPartitionedInclusiveMul:
6402 case glslang::EOpSubgroupPartitionedExclusiveMul:
6403#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006404 if (isFloat) {
6405 opCode = spv::OpGroupNonUniformFMul;
6406 } else {
6407 opCode = spv::OpGroupNonUniformIMul;
6408 }
6409 break;
6410 case glslang::EOpSubgroupMin:
6411 case glslang::EOpSubgroupInclusiveMin:
6412 case glslang::EOpSubgroupExclusiveMin:
6413 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006414#ifdef NV_EXTENSIONS
6415 case glslang::EOpSubgroupPartitionedMin:
6416 case glslang::EOpSubgroupPartitionedInclusiveMin:
6417 case glslang::EOpSubgroupPartitionedExclusiveMin:
6418#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006419 if (isFloat) {
6420 opCode = spv::OpGroupNonUniformFMin;
6421 } else if (isUnsigned) {
6422 opCode = spv::OpGroupNonUniformUMin;
6423 } else {
6424 opCode = spv::OpGroupNonUniformSMin;
6425 }
6426 break;
6427 case glslang::EOpSubgroupMax:
6428 case glslang::EOpSubgroupInclusiveMax:
6429 case glslang::EOpSubgroupExclusiveMax:
6430 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006431#ifdef NV_EXTENSIONS
6432 case glslang::EOpSubgroupPartitionedMax:
6433 case glslang::EOpSubgroupPartitionedInclusiveMax:
6434 case glslang::EOpSubgroupPartitionedExclusiveMax:
6435#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006436 if (isFloat) {
6437 opCode = spv::OpGroupNonUniformFMax;
6438 } else if (isUnsigned) {
6439 opCode = spv::OpGroupNonUniformUMax;
6440 } else {
6441 opCode = spv::OpGroupNonUniformSMax;
6442 }
6443 break;
6444 case glslang::EOpSubgroupAnd:
6445 case glslang::EOpSubgroupInclusiveAnd:
6446 case glslang::EOpSubgroupExclusiveAnd:
6447 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006448#ifdef NV_EXTENSIONS
6449 case glslang::EOpSubgroupPartitionedAnd:
6450 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6451 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6452#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006453 if (isBool) {
6454 opCode = spv::OpGroupNonUniformLogicalAnd;
6455 } else {
6456 opCode = spv::OpGroupNonUniformBitwiseAnd;
6457 }
6458 break;
6459 case glslang::EOpSubgroupOr:
6460 case glslang::EOpSubgroupInclusiveOr:
6461 case glslang::EOpSubgroupExclusiveOr:
6462 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006463#ifdef NV_EXTENSIONS
6464 case glslang::EOpSubgroupPartitionedOr:
6465 case glslang::EOpSubgroupPartitionedInclusiveOr:
6466 case glslang::EOpSubgroupPartitionedExclusiveOr:
6467#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006468 if (isBool) {
6469 opCode = spv::OpGroupNonUniformLogicalOr;
6470 } else {
6471 opCode = spv::OpGroupNonUniformBitwiseOr;
6472 }
6473 break;
6474 case glslang::EOpSubgroupXor:
6475 case glslang::EOpSubgroupInclusiveXor:
6476 case glslang::EOpSubgroupExclusiveXor:
6477 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006478#ifdef NV_EXTENSIONS
6479 case glslang::EOpSubgroupPartitionedXor:
6480 case glslang::EOpSubgroupPartitionedInclusiveXor:
6481 case glslang::EOpSubgroupPartitionedExclusiveXor:
6482#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006483 if (isBool) {
6484 opCode = spv::OpGroupNonUniformLogicalXor;
6485 } else {
6486 opCode = spv::OpGroupNonUniformBitwiseXor;
6487 }
6488 break;
6489 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6490 case glslang::EOpSubgroupQuadSwapHorizontal:
6491 case glslang::EOpSubgroupQuadSwapVertical:
6492 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6493 default: assert(0 && "Unhandled subgroup operation!");
6494 }
6495
John Kessenich149afc32018-08-14 13:31:43 -06006496 // get the right Group Operation
6497 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006498 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006499 default:
6500 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006501 case glslang::EOpSubgroupBallotBitCount:
6502 case glslang::EOpSubgroupAdd:
6503 case glslang::EOpSubgroupMul:
6504 case glslang::EOpSubgroupMin:
6505 case glslang::EOpSubgroupMax:
6506 case glslang::EOpSubgroupAnd:
6507 case glslang::EOpSubgroupOr:
6508 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006509 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006510 break;
6511 case glslang::EOpSubgroupBallotInclusiveBitCount:
6512 case glslang::EOpSubgroupInclusiveAdd:
6513 case glslang::EOpSubgroupInclusiveMul:
6514 case glslang::EOpSubgroupInclusiveMin:
6515 case glslang::EOpSubgroupInclusiveMax:
6516 case glslang::EOpSubgroupInclusiveAnd:
6517 case glslang::EOpSubgroupInclusiveOr:
6518 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006519 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006520 break;
6521 case glslang::EOpSubgroupBallotExclusiveBitCount:
6522 case glslang::EOpSubgroupExclusiveAdd:
6523 case glslang::EOpSubgroupExclusiveMul:
6524 case glslang::EOpSubgroupExclusiveMin:
6525 case glslang::EOpSubgroupExclusiveMax:
6526 case glslang::EOpSubgroupExclusiveAnd:
6527 case glslang::EOpSubgroupExclusiveOr:
6528 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006529 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006530 break;
6531 case glslang::EOpSubgroupClusteredAdd:
6532 case glslang::EOpSubgroupClusteredMul:
6533 case glslang::EOpSubgroupClusteredMin:
6534 case glslang::EOpSubgroupClusteredMax:
6535 case glslang::EOpSubgroupClusteredAnd:
6536 case glslang::EOpSubgroupClusteredOr:
6537 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006538 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006539 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006540#ifdef NV_EXTENSIONS
6541 case glslang::EOpSubgroupPartitionedAdd:
6542 case glslang::EOpSubgroupPartitionedMul:
6543 case glslang::EOpSubgroupPartitionedMin:
6544 case glslang::EOpSubgroupPartitionedMax:
6545 case glslang::EOpSubgroupPartitionedAnd:
6546 case glslang::EOpSubgroupPartitionedOr:
6547 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006548 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006549 break;
6550 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6551 case glslang::EOpSubgroupPartitionedInclusiveMul:
6552 case glslang::EOpSubgroupPartitionedInclusiveMin:
6553 case glslang::EOpSubgroupPartitionedInclusiveMax:
6554 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6555 case glslang::EOpSubgroupPartitionedInclusiveOr:
6556 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006557 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006558 break;
6559 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6560 case glslang::EOpSubgroupPartitionedExclusiveMul:
6561 case glslang::EOpSubgroupPartitionedExclusiveMin:
6562 case glslang::EOpSubgroupPartitionedExclusiveMax:
6563 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6564 case glslang::EOpSubgroupPartitionedExclusiveOr:
6565 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006566 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006567 break;
6568#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006569 }
6570
John Kessenich149afc32018-08-14 13:31:43 -06006571 // build the instruction
6572 std::vector<spv::IdImmediate> spvGroupOperands;
6573
6574 // Every operation begins with the Execution Scope operand.
6575 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6576 spvGroupOperands.push_back(executionScope);
6577
6578 // Next, for all operations that use a Group Operation, push that as an operand.
6579 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006580 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006581 spvGroupOperands.push_back(groupOperand);
6582 }
6583
John Kessenich66011cb2018-03-06 16:12:04 -07006584 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006585 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6586 spv::IdImmediate operand = { true, *opIt };
6587 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006588 }
6589
6590 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006591 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006592 switch (op) {
6593 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006594 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6595 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6596 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6597 }
6598 if (directionId != spv::NoResult) {
6599 spv::IdImmediate direction = { true, directionId };
6600 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006601 }
6602
6603 return builder.createOp(opCode, typeId, spvGroupOperands);
6604}
6605
John Kessenich5e4b1242015-08-06 22:53:06 -06006606spv::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 -06006607{
John Kessenich66011cb2018-03-06 16:12:04 -07006608 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6609 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006610
John Kessenich140f3df2015-06-26 16:58:36 -06006611 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006612 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006613 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006614 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006615 spv::Id typeId0 = 0;
6616 if (consumedOperands > 0)
6617 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006618 spv::Id typeId1 = 0;
6619 if (consumedOperands > 1)
6620 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006621 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006622
6623 switch (op) {
6624 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006625 if (isFloat)
6626 libCall = spv::GLSLstd450FMin;
6627 else if (isUnsigned)
6628 libCall = spv::GLSLstd450UMin;
6629 else
6630 libCall = spv::GLSLstd450SMin;
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::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006634 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006635 break;
6636 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006637 if (isFloat)
6638 libCall = spv::GLSLstd450FMax;
6639 else if (isUnsigned)
6640 libCall = spv::GLSLstd450UMax;
6641 else
6642 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006643 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006644 break;
6645 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006646 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006647 break;
6648 case glslang::EOpDot:
6649 opCode = spv::OpDot;
6650 break;
6651 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006652 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006653 break;
6654
6655 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006656 if (isFloat)
6657 libCall = spv::GLSLstd450FClamp;
6658 else if (isUnsigned)
6659 libCall = spv::GLSLstd450UClamp;
6660 else
6661 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006662 builder.promoteScalar(precision, operands.front(), operands[1]);
6663 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006664 break;
6665 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006666 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6667 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006668 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006669 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006670 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006671 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006672 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006673 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006674 break;
6675 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006676 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006677 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006678 break;
6679 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006680 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006681 builder.promoteScalar(precision, operands[0], operands[2]);
6682 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006683 break;
6684
6685 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006686 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006687 break;
6688 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006689 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006690 break;
6691 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006692 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006693 break;
6694 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006695 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006696 break;
6697 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006698 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006699 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006700 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006701#ifdef AMD_EXTENSIONS
6702 if (typeProxy == glslang::EbtFloat16)
6703 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6704#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006705 libCall = spv::GLSLstd450InterpolateAtSample;
6706 break;
6707 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006708#ifdef AMD_EXTENSIONS
6709 if (typeProxy == glslang::EbtFloat16)
6710 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6711#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006712 libCall = spv::GLSLstd450InterpolateAtOffset;
6713 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006714 case glslang::EOpAddCarry:
6715 opCode = spv::OpIAddCarry;
6716 typeId = builder.makeStructResultType(typeId0, typeId0);
6717 consumedOperands = 2;
6718 break;
6719 case glslang::EOpSubBorrow:
6720 opCode = spv::OpISubBorrow;
6721 typeId = builder.makeStructResultType(typeId0, typeId0);
6722 consumedOperands = 2;
6723 break;
6724 case glslang::EOpUMulExtended:
6725 opCode = spv::OpUMulExtended;
6726 typeId = builder.makeStructResultType(typeId0, typeId0);
6727 consumedOperands = 2;
6728 break;
6729 case glslang::EOpIMulExtended:
6730 opCode = spv::OpSMulExtended;
6731 typeId = builder.makeStructResultType(typeId0, typeId0);
6732 consumedOperands = 2;
6733 break;
6734 case glslang::EOpBitfieldExtract:
6735 if (isUnsigned)
6736 opCode = spv::OpBitFieldUExtract;
6737 else
6738 opCode = spv::OpBitFieldSExtract;
6739 break;
6740 case glslang::EOpBitfieldInsert:
6741 opCode = spv::OpBitFieldInsert;
6742 break;
6743
6744 case glslang::EOpFma:
6745 libCall = spv::GLSLstd450Fma;
6746 break;
6747 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006748 {
6749 libCall = spv::GLSLstd450FrexpStruct;
6750 assert(builder.isPointerType(typeId1));
6751 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006752 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006753#ifdef AMD_EXTENSIONS
6754 if (width == 16)
6755 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6756 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6757#endif
Rex Xu470026f2017-03-29 17:12:40 +08006758 if (builder.getNumComponents(operands[0]) == 1)
6759 frexpIntType = builder.makeIntegerType(width, true);
6760 else
6761 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6762 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6763 consumedOperands = 1;
6764 }
John Kessenich55e7d112015-11-15 21:33:39 -07006765 break;
6766 case glslang::EOpLdexp:
6767 libCall = spv::GLSLstd450Ldexp;
6768 break;
6769
Rex Xu574ab042016-04-14 16:53:07 +08006770 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006771 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006772
John Kessenich66011cb2018-03-06 16:12:04 -07006773 case glslang::EOpSubgroupBroadcast:
6774 case glslang::EOpSubgroupBallotBitExtract:
6775 case glslang::EOpSubgroupShuffle:
6776 case glslang::EOpSubgroupShuffleXor:
6777 case glslang::EOpSubgroupShuffleUp:
6778 case glslang::EOpSubgroupShuffleDown:
6779 case glslang::EOpSubgroupClusteredAdd:
6780 case glslang::EOpSubgroupClusteredMul:
6781 case glslang::EOpSubgroupClusteredMin:
6782 case glslang::EOpSubgroupClusteredMax:
6783 case glslang::EOpSubgroupClusteredAnd:
6784 case glslang::EOpSubgroupClusteredOr:
6785 case glslang::EOpSubgroupClusteredXor:
6786 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006787#ifdef NV_EXTENSIONS
6788 case glslang::EOpSubgroupPartitionedAdd:
6789 case glslang::EOpSubgroupPartitionedMul:
6790 case glslang::EOpSubgroupPartitionedMin:
6791 case glslang::EOpSubgroupPartitionedMax:
6792 case glslang::EOpSubgroupPartitionedAnd:
6793 case glslang::EOpSubgroupPartitionedOr:
6794 case glslang::EOpSubgroupPartitionedXor:
6795 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6796 case glslang::EOpSubgroupPartitionedInclusiveMul:
6797 case glslang::EOpSubgroupPartitionedInclusiveMin:
6798 case glslang::EOpSubgroupPartitionedInclusiveMax:
6799 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6800 case glslang::EOpSubgroupPartitionedInclusiveOr:
6801 case glslang::EOpSubgroupPartitionedInclusiveXor:
6802 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6803 case glslang::EOpSubgroupPartitionedExclusiveMul:
6804 case glslang::EOpSubgroupPartitionedExclusiveMin:
6805 case glslang::EOpSubgroupPartitionedExclusiveMax:
6806 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6807 case glslang::EOpSubgroupPartitionedExclusiveOr:
6808 case glslang::EOpSubgroupPartitionedExclusiveXor:
6809#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006810 return createSubgroupOperation(op, typeId, operands, typeProxy);
6811
Rex Xu9d93a232016-05-05 12:30:44 +08006812#ifdef AMD_EXTENSIONS
6813 case glslang::EOpSwizzleInvocations:
6814 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6815 libCall = spv::SwizzleInvocationsAMD;
6816 break;
6817 case glslang::EOpSwizzleInvocationsMasked:
6818 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6819 libCall = spv::SwizzleInvocationsMaskedAMD;
6820 break;
6821 case glslang::EOpWriteInvocation:
6822 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6823 libCall = spv::WriteInvocationAMD;
6824 break;
6825
6826 case glslang::EOpMin3:
6827 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6828 if (isFloat)
6829 libCall = spv::FMin3AMD;
6830 else {
6831 if (isUnsigned)
6832 libCall = spv::UMin3AMD;
6833 else
6834 libCall = spv::SMin3AMD;
6835 }
6836 break;
6837 case glslang::EOpMax3:
6838 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6839 if (isFloat)
6840 libCall = spv::FMax3AMD;
6841 else {
6842 if (isUnsigned)
6843 libCall = spv::UMax3AMD;
6844 else
6845 libCall = spv::SMax3AMD;
6846 }
6847 break;
6848 case glslang::EOpMid3:
6849 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6850 if (isFloat)
6851 libCall = spv::FMid3AMD;
6852 else {
6853 if (isUnsigned)
6854 libCall = spv::UMid3AMD;
6855 else
6856 libCall = spv::SMid3AMD;
6857 }
6858 break;
6859
6860 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006861 if (typeProxy == glslang::EbtFloat16)
6862 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006863 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6864 libCall = spv::InterpolateAtVertexAMD;
6865 break;
6866#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006867 case glslang::EOpBarrier:
6868 {
6869 // This is for the extended controlBarrier function, with four operands.
6870 // The unextended barrier() goes through createNoArgOperation.
6871 assert(operands.size() == 4);
6872 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6873 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6874 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6875 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6876 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6877 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6878 }
6879 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6880 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6881 }
6882 return 0;
6883 }
6884 break;
6885 case glslang::EOpMemoryBarrier:
6886 {
6887 // This is for the extended memoryBarrier function, with three operands.
6888 // The unextended memoryBarrier() goes through createNoArgOperation.
6889 assert(operands.size() == 3);
6890 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6891 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6892 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6893 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6894 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6895 }
6896 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6897 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6898 }
6899 return 0;
6900 }
6901 break;
Chao Chen3c366992018-09-19 11:41:59 -07006902
6903#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006904 case glslang::EOpReportIntersectionNV:
6905 {
6906 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07006907 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07006908 }
6909 break;
6910 case glslang::EOpTraceNV:
6911 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07006912 builder.createNoResultOp(spv::OpTraceNV, operands);
6913 return 0;
6914 }
6915 break;
6916 case glslang::EOpExecuteCallableNV:
6917 {
6918 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07006919 return 0;
6920 }
6921 break;
Chao Chen3c366992018-09-19 11:41:59 -07006922 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6923 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6924 return 0;
6925#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006926 default:
6927 return 0;
6928 }
6929
6930 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006931 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006932 // Use an extended instruction from the standard library.
6933 // Construct the call arguments, without modifying the original operands vector.
6934 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6935 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006936 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01006937 } else if (opCode == spv::OpDot && !isFloat) {
6938 // int dot(int, int)
6939 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
6940 const int componentCount = builder.getNumComponents(operands[0]);
6941 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
6942 builder.setPrecision(mulOp, precision);
6943 id = builder.createCompositeExtract(mulOp, typeId, 0);
6944 for (int i = 1; i < componentCount; ++i) {
6945 builder.setPrecision(id, precision);
6946 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
6947 }
John Kessenich2359bd02015-12-06 19:29:11 -07006948 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006949 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006950 case 0:
6951 // should all be handled by visitAggregate and createNoArgOperation
6952 assert(0);
6953 return 0;
6954 case 1:
6955 // should all be handled by createUnaryOperation
6956 assert(0);
6957 return 0;
6958 case 2:
6959 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6960 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006961 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006962 // anything 3 or over doesn't have l-value operands, so all should be consumed
6963 assert(consumedOperands == operands.size());
6964 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006965 break;
6966 }
6967 }
6968
John Kessenich55e7d112015-11-15 21:33:39 -07006969 // Decode the return types that were structures
6970 switch (op) {
6971 case glslang::EOpAddCarry:
6972 case glslang::EOpSubBorrow:
6973 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6974 id = builder.createCompositeExtract(id, typeId0, 0);
6975 break;
6976 case glslang::EOpUMulExtended:
6977 case glslang::EOpIMulExtended:
6978 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6979 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6980 break;
6981 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006982 {
6983 assert(operands.size() == 2);
6984 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6985 // "exp" is floating-point type (from HLSL intrinsic)
6986 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6987 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6988 builder.createStore(member1, operands[1]);
6989 } else
6990 // "exp" is integer type (from GLSL built-in function)
6991 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6992 id = builder.createCompositeExtract(id, typeId0, 0);
6993 }
John Kessenich55e7d112015-11-15 21:33:39 -07006994 break;
6995 default:
6996 break;
6997 }
6998
John Kessenich32cfd492016-02-02 12:37:46 -07006999 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007000}
7001
Rex Xu9d93a232016-05-05 12:30:44 +08007002// Intrinsics with no arguments (or no return value, and no precision).
7003spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007004{
Jeff Bolz36831c92018-09-05 10:11:41 -05007005 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7006 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007007
7008 switch (op) {
7009 case glslang::EOpEmitVertex:
7010 builder.createNoResultOp(spv::OpEmitVertex);
7011 return 0;
7012 case glslang::EOpEndPrimitive:
7013 builder.createNoResultOp(spv::OpEndPrimitive);
7014 return 0;
7015 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007016 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007017 if (glslangIntermediate->usingVulkanMemoryModel()) {
7018 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7019 spv::MemorySemanticsOutputMemoryKHRMask |
7020 spv::MemorySemanticsAcquireReleaseMask);
7021 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7022 } else {
7023 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7024 }
John Kessenich82979362017-12-11 04:02:24 -07007025 } else {
7026 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7027 spv::MemorySemanticsWorkgroupMemoryMask |
7028 spv::MemorySemanticsAcquireReleaseMask);
7029 }
John Kessenich140f3df2015-06-26 16:58:36 -06007030 return 0;
7031 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007032 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7033 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007034 return 0;
7035 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007036 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7037 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007038 return 0;
7039 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007040 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7041 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007042 return 0;
7043 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007044 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7045 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007046 return 0;
7047 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007048 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7049 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007050 return 0;
7051 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007052 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7053 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007054 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007055 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007056 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007057 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007058 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007059 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007060 case glslang::EOpDeviceMemoryBarrier:
7061 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7062 spv::MemorySemanticsImageMemoryMask |
7063 spv::MemorySemanticsAcquireReleaseMask);
7064 return 0;
7065 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7066 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7067 spv::MemorySemanticsImageMemoryMask |
7068 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007069 return 0;
7070 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007071 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7072 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007073 return 0;
7074 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007075 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7076 spv::MemorySemanticsWorkgroupMemoryMask |
7077 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007078 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007079 case glslang::EOpSubgroupBarrier:
7080 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7081 spv::MemorySemanticsAcquireReleaseMask);
7082 return spv::NoResult;
7083 case glslang::EOpSubgroupMemoryBarrier:
7084 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7085 spv::MemorySemanticsAcquireReleaseMask);
7086 return spv::NoResult;
7087 case glslang::EOpSubgroupMemoryBarrierBuffer:
7088 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7089 spv::MemorySemanticsAcquireReleaseMask);
7090 return spv::NoResult;
7091 case glslang::EOpSubgroupMemoryBarrierImage:
7092 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7093 spv::MemorySemanticsAcquireReleaseMask);
7094 return spv::NoResult;
7095 case glslang::EOpSubgroupMemoryBarrierShared:
7096 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7097 spv::MemorySemanticsAcquireReleaseMask);
7098 return spv::NoResult;
7099 case glslang::EOpSubgroupElect: {
7100 std::vector<spv::Id> operands;
7101 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7102 }
Rex Xu9d93a232016-05-05 12:30:44 +08007103#ifdef AMD_EXTENSIONS
7104 case glslang::EOpTime:
7105 {
7106 std::vector<spv::Id> args; // Dummy arguments
7107 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7108 return builder.setPrecision(id, precision);
7109 }
7110#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007111#ifdef NV_EXTENSIONS
7112 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007113 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007114 return 0;
7115 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007116 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007117 return 0;
7118#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007119 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007120 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007121 return 0;
7122 }
7123}
7124
7125spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7126{
John Kessenich2f273362015-07-18 22:34:27 -06007127 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007128 spv::Id id;
7129 if (symbolValues.end() != iter) {
7130 id = iter->second;
7131 return id;
7132 }
7133
7134 // it was not found, create it
7135 id = createSpvVariable(symbol);
7136 symbolValues[symbol->getId()] = id;
7137
Rex Xuc884b4a2016-06-29 15:03:44 +08007138 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007139 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7140 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7141 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007142#ifdef NV_EXTENSIONS
7143 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7144#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007145 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007146 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007147 if (symbol->getQualifier().hasIndex())
7148 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7149 if (symbol->getQualifier().hasComponent())
7150 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007151 // atomic counters use this:
7152 if (symbol->getQualifier().hasOffset())
7153 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007154 }
7155
scygan2c864272016-05-18 18:09:17 +02007156 if (symbol->getQualifier().hasLocation())
7157 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007158 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007159 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007160 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007161 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007162 }
John Kessenich140f3df2015-06-26 16:58:36 -06007163 if (symbol->getQualifier().hasSet())
7164 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007165 else if (IsDescriptorResource(symbol->getType())) {
7166 // default to 0
7167 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7168 }
John Kessenich140f3df2015-06-26 16:58:36 -06007169 if (symbol->getQualifier().hasBinding())
7170 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007171 else if (IsDescriptorResource(symbol->getType())) {
7172 // default to 0
7173 builder.addDecoration(id, spv::DecorationBinding, 0);
7174 }
John Kessenich6c292d32016-02-15 20:58:50 -07007175 if (symbol->getQualifier().hasAttachment())
7176 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007177 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007178 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007179 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007180 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007181 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7182 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7183 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7184 }
7185 if (symbol->getQualifier().hasXfbOffset())
7186 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007187 }
7188
Rex Xu1da878f2016-02-21 20:59:01 +08007189 if (symbol->getType().isImage()) {
7190 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007191 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007192 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007193 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007194 }
7195
John Kessenich140f3df2015-06-26 16:58:36 -06007196 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007197 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007198 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007199 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007200
John Kessenich5611c6d2018-04-05 11:25:02 -06007201 // nonuniform
7202 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7203
John Kessenichecba76f2017-01-06 00:34:48 -07007204#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007205 if (builtIn == spv::BuiltInSampleMask) {
7206 spv::Decoration decoration;
7207 // GL_NV_sample_mask_override_coverage extension
7208 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007209 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007210 else
7211 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007212 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007213 if (decoration != spv::DecorationMax) {
7214 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7215 }
7216 }
chaoc771d89f2017-01-13 01:10:53 -08007217 else if (builtIn == spv::BuiltInLayer) {
7218 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007219 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007220 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007221 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7222 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7223 }
John Kessenichb41bff62017-08-11 13:07:17 -06007224 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007225 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7226 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007227 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7228 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7229 }
7230 }
7231
chaoc6e5acae2016-12-20 13:28:52 -08007232 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007233 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007234 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007235 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7236 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007237 if (symbol->getQualifier().pervertexNV) {
7238 builder.addDecoration(id, spv::DecorationPerVertexNV);
7239 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7240 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7241 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007242#endif
7243
John Kessenich5d610ee2018-03-07 18:05:55 -07007244 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7245 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7246 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7247 symbol->getType().getQualifier().semanticName);
7248 }
7249
John Kessenich140f3df2015-06-26 16:58:36 -06007250 return id;
7251}
7252
Chao Chen3c366992018-09-19 11:41:59 -07007253#ifdef NV_EXTENSIONS
7254// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7255void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7256{
7257 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007258 if (qualifier.perPrimitiveNV) {
7259 // Need to add capability/extension for fragment shader.
7260 // Mesh shader already adds this by default.
7261 if (glslangIntermediate->getStage() == EShLangFragment) {
7262 builder.addCapability(spv::CapabilityMeshShadingNV);
7263 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7264 }
Chao Chen3c366992018-09-19 11:41:59 -07007265 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007266 }
Chao Chen3c366992018-09-19 11:41:59 -07007267 if (qualifier.perViewNV)
7268 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7269 if (qualifier.perTaskNV)
7270 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7271 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007272 if (qualifier.perPrimitiveNV) {
7273 // Need to add capability/extension for fragment shader.
7274 // Mesh shader already adds this by default.
7275 if (glslangIntermediate->getStage() == EShLangFragment) {
7276 builder.addCapability(spv::CapabilityMeshShadingNV);
7277 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7278 }
Chao Chen3c366992018-09-19 11:41:59 -07007279 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007280 }
Chao Chen3c366992018-09-19 11:41:59 -07007281 if (qualifier.perViewNV)
7282 builder.addDecoration(id, spv::DecorationPerViewNV);
7283 if (qualifier.perTaskNV)
7284 builder.addDecoration(id, spv::DecorationPerTaskNV);
7285 }
7286}
7287#endif
7288
John Kessenich55e7d112015-11-15 21:33:39 -07007289// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007290// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007291//
7292// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7293//
7294// Recursively walk the nodes. The nodes form a tree whose leaves are
7295// regular constants, which themselves are trees that createSpvConstant()
7296// recursively walks. So, this function walks the "top" of the tree:
7297// - emit specialization constant-building instructions for specConstant
7298// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007299spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007300{
John Kessenich7cc0e282016-03-20 00:46:02 -06007301 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007302
qining4f4bb812016-04-03 23:55:17 -04007303 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007304 if (! node.getQualifier().specConstant) {
7305 // hand off to the non-spec-constant path
7306 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7307 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007308 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007309 nextConst, false);
7310 }
7311
7312 // We now know we have a specialization constant to build
7313
John Kessenichd94c0032016-05-30 19:29:40 -06007314 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007315 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7316 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7317 std::vector<spv::Id> dimConstId;
7318 for (int dim = 0; dim < 3; ++dim) {
7319 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7320 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007321 if (specConst) {
7322 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7323 glslangIntermediate->getLocalSizeSpecId(dim));
7324 }
qining4f4bb812016-04-03 23:55:17 -04007325 }
7326 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7327 }
7328
7329 // An AST node labelled as specialization constant should be a symbol node.
7330 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7331 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007332 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007333 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007334 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7335 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7336 // will set the builder into spec constant op instruction generating mode.
7337 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007338 result = accessChainLoad(sub_tree->getType());
7339 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007340 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007341 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007342 } else {
7343 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007344 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007345 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007346 builder.addName(result, sn->getName().c_str());
7347 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007348 }
qining4f4bb812016-04-03 23:55:17 -04007349
7350 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7351 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007352 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007353 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007354}
7355
John Kessenich140f3df2015-06-26 16:58:36 -06007356// Use 'consts' as the flattened glslang source of scalar constants to recursively
7357// build the aggregate SPIR-V constant.
7358//
7359// If there are not enough elements present in 'consts', 0 will be substituted;
7360// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7361//
qining08408382016-03-21 09:51:37 -04007362spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007363{
7364 // vector of constants for SPIR-V
7365 std::vector<spv::Id> spvConsts;
7366
7367 // Type is used for struct and array constants
7368 spv::Id typeId = convertGlslangToSpvType(glslangType);
7369
7370 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007371 glslang::TType elementType(glslangType, 0);
7372 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007373 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007374 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007375 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007376 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007377 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007378 } else if (glslangType.getStruct()) {
7379 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7380 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007381 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007382 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007383 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7384 bool zero = nextConst >= consts.size();
7385 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007386 case glslang::EbtInt8:
7387 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7388 break;
7389 case glslang::EbtUint8:
7390 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7391 break;
7392 case glslang::EbtInt16:
7393 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7394 break;
7395 case glslang::EbtUint16:
7396 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7397 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007398 case glslang::EbtInt:
7399 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7400 break;
7401 case glslang::EbtUint:
7402 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7403 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007404 case glslang::EbtInt64:
7405 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7406 break;
7407 case glslang::EbtUint64:
7408 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7409 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007410 case glslang::EbtFloat:
7411 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7412 break;
7413 case glslang::EbtDouble:
7414 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7415 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007416 case glslang::EbtFloat16:
7417 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7418 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007419 case glslang::EbtBool:
7420 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7421 break;
7422 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007423 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007424 break;
7425 }
7426 ++nextConst;
7427 }
7428 } else {
7429 // we have a non-aggregate (scalar) constant
7430 bool zero = nextConst >= consts.size();
7431 spv::Id scalar = 0;
7432 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007433 case glslang::EbtInt8:
7434 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7435 break;
7436 case glslang::EbtUint8:
7437 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7438 break;
7439 case glslang::EbtInt16:
7440 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7441 break;
7442 case glslang::EbtUint16:
7443 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007445 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007446 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007447 break;
7448 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007449 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007450 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007451 case glslang::EbtInt64:
7452 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7453 break;
7454 case glslang::EbtUint64:
7455 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7456 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007457 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007458 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007459 break;
7460 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007461 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007462 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007463 case glslang::EbtFloat16:
7464 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7465 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007466 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007467 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007468 break;
7469 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007470 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007471 break;
7472 }
7473 ++nextConst;
7474 return scalar;
7475 }
7476
7477 return builder.makeCompositeConstant(typeId, spvConsts);
7478}
7479
John Kessenich7c1aa102015-10-15 13:29:11 -06007480// Return true if the node is a constant or symbol whose reading has no
7481// non-trivial observable cost or effect.
7482bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7483{
7484 // don't know what this is
7485 if (node == nullptr)
7486 return false;
7487
7488 // a constant is safe
7489 if (node->getAsConstantUnion() != nullptr)
7490 return true;
7491
7492 // not a symbol means non-trivial
7493 if (node->getAsSymbolNode() == nullptr)
7494 return false;
7495
7496 // a symbol, depends on what's being read
7497 switch (node->getType().getQualifier().storage) {
7498 case glslang::EvqTemporary:
7499 case glslang::EvqGlobal:
7500 case glslang::EvqIn:
7501 case glslang::EvqInOut:
7502 case glslang::EvqConst:
7503 case glslang::EvqConstReadOnly:
7504 case glslang::EvqUniform:
7505 return true;
7506 default:
7507 return false;
7508 }
qining25262b32016-05-06 17:25:16 -04007509}
John Kessenich7c1aa102015-10-15 13:29:11 -06007510
7511// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007512// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007513// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007514// Return true if trivial.
7515bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7516{
7517 if (node == nullptr)
7518 return false;
7519
John Kessenich84cc15f2017-05-24 16:44:47 -06007520 // count non scalars as trivial, as well as anything coming from HLSL
7521 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007522 return true;
7523
John Kessenich7c1aa102015-10-15 13:29:11 -06007524 // symbols and constants are trivial
7525 if (isTrivialLeaf(node))
7526 return true;
7527
7528 // otherwise, it needs to be a simple operation or one or two leaf nodes
7529
7530 // not a simple operation
7531 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7532 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7533 if (binaryNode == nullptr && unaryNode == nullptr)
7534 return false;
7535
7536 // not on leaf nodes
7537 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7538 return false;
7539
7540 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7541 return false;
7542 }
7543
7544 switch (node->getAsOperator()->getOp()) {
7545 case glslang::EOpLogicalNot:
7546 case glslang::EOpConvIntToBool:
7547 case glslang::EOpConvUintToBool:
7548 case glslang::EOpConvFloatToBool:
7549 case glslang::EOpConvDoubleToBool:
7550 case glslang::EOpEqual:
7551 case glslang::EOpNotEqual:
7552 case glslang::EOpLessThan:
7553 case glslang::EOpGreaterThan:
7554 case glslang::EOpLessThanEqual:
7555 case glslang::EOpGreaterThanEqual:
7556 case glslang::EOpIndexDirect:
7557 case glslang::EOpIndexDirectStruct:
7558 case glslang::EOpLogicalXor:
7559 case glslang::EOpAny:
7560 case glslang::EOpAll:
7561 return true;
7562 default:
7563 return false;
7564 }
7565}
7566
7567// Emit short-circuiting code, where 'right' is never evaluated unless
7568// the left side is true (for &&) or false (for ||).
7569spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7570{
7571 spv::Id boolTypeId = builder.makeBoolType();
7572
7573 // emit left operand
7574 builder.clearAccessChain();
7575 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007576 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007577
7578 // Operands to accumulate OpPhi operands
7579 std::vector<spv::Id> phiOperands;
7580 // accumulate left operand's phi information
7581 phiOperands.push_back(leftId);
7582 phiOperands.push_back(builder.getBuildPoint()->getId());
7583
7584 // Make the two kinds of operation symmetric with a "!"
7585 // || => emit "if (! left) result = right"
7586 // && => emit "if ( left) result = right"
7587 //
7588 // TODO: this runtime "not" for || could be avoided by adding functionality
7589 // to 'builder' to have an "else" without an "then"
7590 if (op == glslang::EOpLogicalOr)
7591 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7592
7593 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007594 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007595
7596 // emit right operand as the "then" part of the "if"
7597 builder.clearAccessChain();
7598 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007599 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007600
7601 // accumulate left operand's phi information
7602 phiOperands.push_back(rightId);
7603 phiOperands.push_back(builder.getBuildPoint()->getId());
7604
7605 // finish the "if"
7606 ifBuilder.makeEndIf();
7607
7608 // phi together the two results
7609 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7610}
7611
Frank Henigman541f7bb2018-01-16 00:18:26 -05007612#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007613// Return type Id of the imported set of extended instructions corresponds to the name.
7614// Import this set if it has not been imported yet.
7615spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7616{
7617 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7618 return extBuiltinMap[name];
7619 else {
Rex Xu51596642016-09-21 18:56:12 +08007620 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007621 spv::Id extBuiltins = builder.import(name);
7622 extBuiltinMap[name] = extBuiltins;
7623 return extBuiltins;
7624 }
7625}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007626#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007627
John Kessenich140f3df2015-06-26 16:58:36 -06007628}; // end anonymous namespace
7629
7630namespace glslang {
7631
John Kessenich68d78fd2015-07-12 19:28:10 -06007632void GetSpirvVersion(std::string& version)
7633{
John Kessenich9e55f632015-07-15 10:03:39 -06007634 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007635 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007636 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007637 version = buf;
7638}
7639
John Kessenicha372a3e2017-11-02 22:32:14 -06007640// For low-order part of the generator's magic number. Bump up
7641// when there is a change in the style (e.g., if SSA form changes,
7642// or a different instruction sequence to do something gets used).
7643int GetSpirvGeneratorVersion()
7644{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007645 // return 1; // start
7646 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007647 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007648 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007649 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007650 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7651 // versions 4 and 6 each generate OpArrayLength as it has long been done
7652 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007653}
7654
John Kessenich140f3df2015-06-26 16:58:36 -06007655// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007656void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007657{
7658 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007659 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007660 if (out.fail())
7661 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007662 for (int i = 0; i < (int)spirv.size(); ++i) {
7663 unsigned int word = spirv[i];
7664 out.write((const char*)&word, 4);
7665 }
7666 out.close();
7667}
7668
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007669// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007670void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007671{
7672 std::ofstream out;
7673 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007674 if (out.fail())
7675 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007676 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007677 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007678 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007679 if (varName != nullptr) {
7680 out << "\t #pragma once" << std::endl;
7681 out << "const uint32_t " << varName << "[] = {" << std::endl;
7682 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007683 const int WORDS_PER_LINE = 8;
7684 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7685 out << "\t";
7686 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7687 const unsigned int word = spirv[i + j];
7688 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7689 if (i + j + 1 < (int)spirv.size()) {
7690 out << ",";
7691 }
7692 }
7693 out << std::endl;
7694 }
Flavio15017db2017-02-15 14:29:33 -08007695 if (varName != nullptr) {
7696 out << "};";
7697 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007698 out.close();
7699}
7700
John Kessenich140f3df2015-06-26 16:58:36 -06007701//
7702// Set up the glslang traversal
7703//
John Kessenich4e11b612018-08-30 16:56:59 -06007704void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007705{
Lei Zhang17535f72016-05-04 15:55:59 -04007706 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007707 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007708}
7709
John Kessenich4e11b612018-08-30 16:56:59 -06007710void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007711 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007712{
John Kessenich140f3df2015-06-26 16:58:36 -06007713 TIntermNode* root = intermediate.getTreeRoot();
7714
7715 if (root == 0)
7716 return;
7717
John Kessenich4e11b612018-08-30 16:56:59 -06007718 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007719 if (options == nullptr)
7720 options = &defaultOptions;
7721
John Kessenich4e11b612018-08-30 16:56:59 -06007722 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007723
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007724 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007725 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007726 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007727 it.dumpSpv(spirv);
7728
GregFfb03a552018-03-29 11:49:14 -06007729#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007730 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7731 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007732 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007733 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007734
John Kessenich4e11b612018-08-30 16:56:59 -06007735 if (options->validate)
7736 SpirvToolsValidate(intermediate, spirv, logger);
7737
John Kessenich717c80a2018-08-23 15:17:10 -06007738 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007739 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007740
GregFcd1f1692017-09-21 18:40:22 -06007741#endif
7742
John Kessenich4e11b612018-08-30 16:56:59 -06007743 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007744}
7745
7746}; // end namespace glslang