blob: b3f7df78b48bb52fbb44355e70a642bb62821126 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700197#ifdef NV_EXTENSIONS
198 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
199#endif
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
229 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800230 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600231
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600233 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700235 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
237 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700239 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNVX;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNVX;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNVX;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNVX;
283 case EShLangMissNV: return spv::ExecutionModelMissNVX;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNVX;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
341#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600342 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 break;
345 }
346 }
347
John Kessenich4016e382016-07-15 11:53:56 -0600348 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600349}
350
Rex Xu1da878f2016-02-21 20:59:01 +0800351// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500352void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800353{
Jeff Bolz36831c92018-09-05 10:11:41 -0500354 if (!useVulkanMemoryModel) {
355 if (qualifier.coherent)
356 memory.push_back(spv::DecorationCoherent);
357 if (qualifier.volatil) {
358 memory.push_back(spv::DecorationVolatile);
359 memory.push_back(spv::DecorationCoherent);
360 }
John Kessenich14b85d32018-06-04 15:36:03 -0600361 }
Rex Xu1da878f2016-02-21 20:59:01 +0800362 if (qualifier.restrict)
363 memory.push_back(spv::DecorationRestrict);
364 if (qualifier.readonly)
365 memory.push_back(spv::DecorationNonWritable);
366 if (qualifier.writeonly)
367 memory.push_back(spv::DecorationNonReadable);
368}
369
John Kessenich140f3df2015-06-26 16:58:36 -0600370// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700371spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
373 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700374 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600375 case glslang::ElmRowMajor:
376 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700377 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600378 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 default:
380 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 } else {
384 switch (type.getBasicType()) {
385 default:
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 break;
388 case glslang::EbtBlock:
389 switch (type.getQualifier().storage) {
390 case glslang::EvqUniform:
391 case glslang::EvqBuffer:
392 switch (type.getQualifier().layoutPacking) {
393 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600394 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
395 default:
John Kessenich4016e382016-07-15 11:53:56 -0600396 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 }
398 case glslang::EvqVaryingIn:
399 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700400 if (type.getQualifier().isTaskMemory()) {
401 switch (type.getQualifier().layoutPacking) {
402 case glslang::ElpShared: return spv::DecorationGLSLShared;
403 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
404 default: break;
405 }
406 } else {
407 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
408 }
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700410#ifdef NV_EXTENSIONS
411 case glslang::EvqPayloadNV:
412 case glslang::EvqPayloadInNV:
413 case glslang::EvqHitAttrNV:
414 return spv::DecorationMax;
415#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600416 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700417 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 }
420 }
421 }
422}
423
424// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600425// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700426// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800427spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600428{
Rex Xubbceed72016-05-21 09:40:44 +0800429 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700430 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800432 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700433 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600435 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800436#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800437 else if (qualifier.explicitInterp) {
438 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800439 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800440 }
Rex Xu9d93a232016-05-05 12:30:44 +0800441#endif
Rex Xubbceed72016-05-21 09:40:44 +0800442 else
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800444}
445
446// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600447// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800448// should be applied.
449spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
450{
451 if (qualifier.patch)
452 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700453 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600454 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700455 else if (qualifier.sample) {
456 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600457 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700458 } else
John Kessenich4016e382016-07-15 11:53:56 -0600459 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600460}
461
John Kessenich92187592016-02-01 13:45:25 -0700462// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700463spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600464{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700465 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600466 return spv::DecorationInvariant;
467 else
John Kessenich4016e382016-07-15 11:53:56 -0600468 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600469}
470
qining9220dbb2016-05-04 17:34:38 -0400471// If glslang type is noContraction, return SPIR-V NoContraction decoration.
472spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
473{
474 if (qualifier.noContraction)
475 return spv::DecorationNoContraction;
476 else
John Kessenich4016e382016-07-15 11:53:56 -0600477 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400478}
479
John Kessenich5611c6d2018-04-05 11:25:02 -0600480// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
481spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
482{
483 if (qualifier.isNonUniform()) {
484 builder.addExtension("SPV_EXT_descriptor_indexing");
485 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
486 return spv::DecorationNonUniformEXT;
487 } else
488 return spv::DecorationMax;
489}
490
Jeff Bolz36831c92018-09-05 10:11:41 -0500491spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
492{
493 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
494 return spv::MemoryAccessMaskNone;
495 }
496 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
497 if (coherentFlags.volatil ||
498 coherentFlags.coherent ||
499 coherentFlags.devicecoherent ||
500 coherentFlags.queuefamilycoherent ||
501 coherentFlags.workgroupcoherent ||
502 coherentFlags.subgroupcoherent) {
503 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
504 spv::MemoryAccessMakePointerVisibleKHRMask;
505 }
506 if (coherentFlags.nonprivate) {
507 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
508 }
509 if (coherentFlags.volatil) {
510 mask = mask | spv::MemoryAccessVolatileMask;
511 }
512 if (mask != spv::MemoryAccessMaskNone) {
513 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
514 }
515 return mask;
516}
517
518spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
519{
520 if (!glslangIntermediate->usingVulkanMemoryModel()) {
521 return spv::ImageOperandsMaskNone;
522 }
523 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
524 if (coherentFlags.volatil ||
525 coherentFlags.coherent ||
526 coherentFlags.devicecoherent ||
527 coherentFlags.queuefamilycoherent ||
528 coherentFlags.workgroupcoherent ||
529 coherentFlags.subgroupcoherent) {
530 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
531 spv::ImageOperandsMakeTexelVisibleKHRMask;
532 }
533 if (coherentFlags.nonprivate) {
534 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
535 }
536 if (coherentFlags.volatil) {
537 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
538 }
539 if (mask != spv::ImageOperandsMaskNone) {
540 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
541 }
542 return mask;
543}
544
545spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
546{
547 spv::Builder::AccessChain::CoherentFlags flags;
548 flags.coherent = type.getQualifier().coherent;
549 flags.devicecoherent = type.getQualifier().devicecoherent;
550 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
551 // shared variables are implicitly workgroupcoherent in GLSL.
552 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
553 type.getQualifier().storage == glslang::EvqShared;
554 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
555 // *coherent variables are implicitly nonprivate in GLSL
556 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500557 flags.subgroupcoherent ||
558 flags.workgroupcoherent ||
559 flags.queuefamilycoherent ||
560 flags.devicecoherent ||
561 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500562 flags.volatil = type.getQualifier().volatil;
563 flags.isImage = type.getBasicType() == glslang::EbtSampler;
564 return flags;
565}
566
567spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
568{
569 spv::Scope scope;
570 if (coherentFlags.coherent) {
571 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
572 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
573 } else if (coherentFlags.devicecoherent) {
574 scope = spv::ScopeDevice;
575 } else if (coherentFlags.queuefamilycoherent) {
576 scope = spv::ScopeQueueFamilyKHR;
577 } else if (coherentFlags.workgroupcoherent) {
578 scope = spv::ScopeWorkgroup;
579 } else if (coherentFlags.subgroupcoherent) {
580 scope = spv::ScopeSubgroup;
581 } else {
582 scope = spv::ScopeMax;
583 }
584 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
585 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
586 }
587 return scope;
588}
589
David Netoa901ffe2016-06-08 14:11:40 +0100590// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
591// associated capabilities when required. For some built-in variables, a capability
592// is generated only when using the variable in an executable instruction, but not when
593// just declaring a struct member variable with it. This is true for PointSize,
594// ClipDistance, and CullDistance.
595spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600596{
597 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700598 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600599 // Defer adding the capability until the built-in is actually used.
600 if (! memberDeclaration) {
601 switch (glslangIntermediate->getStage()) {
602 case EShLangGeometry:
603 builder.addCapability(spv::CapabilityGeometryPointSize);
604 break;
605 case EShLangTessControl:
606 case EShLangTessEvaluation:
607 builder.addCapability(spv::CapabilityTessellationPointSize);
608 break;
609 default:
610 break;
611 }
John Kessenich92187592016-02-01 13:45:25 -0700612 }
613 return spv::BuiltInPointSize;
614
John Kessenichebb50532016-05-16 19:22:05 -0600615 // These *Distance capabilities logically belong here, but if the member is declared and
616 // then never used, consumers of SPIR-V prefer the capability not be declared.
617 // They are now generated when used, rather than here when declared.
618 // Potentially, the specification should be more clear what the minimum
619 // use needed is to trigger the capability.
620 //
John Kessenich92187592016-02-01 13:45:25 -0700621 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100622 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800623 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700624 return spv::BuiltInClipDistance;
625
626 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInCullDistance;
630
631 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600632 builder.addCapability(spv::CapabilityMultiViewport);
633 if (glslangIntermediate->getStage() == EShLangVertex ||
634 glslangIntermediate->getStage() == EShLangTessControl ||
635 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800636
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
638 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800639 }
John Kessenich92187592016-02-01 13:45:25 -0700640 return spv::BuiltInViewportIndex;
641
John Kessenich5e801132016-02-15 11:09:46 -0700642 case glslang::EbvSampleId:
643 builder.addCapability(spv::CapabilitySampleRateShading);
644 return spv::BuiltInSampleId;
645
646 case glslang::EbvSamplePosition:
647 builder.addCapability(spv::CapabilitySampleRateShading);
648 return spv::BuiltInSamplePosition;
649
650 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700651 return spv::BuiltInSampleMask;
652
John Kessenich78a45572016-07-08 14:05:15 -0600653 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700654#ifdef NV_EXTENSIONS
655 if (glslangIntermediate->getStage() == EShLangMeshNV) {
656 return spv::BuiltInLayer;
657 }
658#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600659 builder.addCapability(spv::CapabilityGeometry);
660 if (glslangIntermediate->getStage() == EShLangVertex ||
661 glslangIntermediate->getStage() == EShLangTessControl ||
662 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800663
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
665 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800666 }
John Kessenich78a45572016-07-08 14:05:15 -0600667 return spv::BuiltInLayer;
668
John Kessenich140f3df2015-06-26 16:58:36 -0600669 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600670 case glslang::EbvVertexId: return spv::BuiltInVertexId;
671 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700672 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
673 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800674
John Kessenichda581a22015-10-14 14:10:30 -0600675 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700676 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800677 builder.addCapability(spv::CapabilityDrawParameters);
678 return spv::BuiltInBaseVertex;
679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
690 case glslang::EbvPrimitiveId:
691 if (glslangIntermediate->getStage() == EShLangFragment)
692 builder.addCapability(spv::CapabilityGeometry);
693 return spv::BuiltInPrimitiveId;
694
Rex Xu37cdcee2017-06-29 17:46:34 +0800695 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800696 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
697 builder.addCapability(spv::CapabilityStencilExportEXT);
698 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800699
John Kessenich140f3df2015-06-26 16:58:36 -0600700 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600701 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
702 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
703 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
704 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
705 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
706 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
707 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600708 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
709 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
710 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
711 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
712 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
713 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
714 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
715 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800716
Rex Xu574ab042016-04-14 16:53:07 +0800717 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800718 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800719 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
720 return spv::BuiltInSubgroupSize;
721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupLocalInvocationId;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupEqMaskKHR;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupGeMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGtMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupLeMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLtMaskKHR;
751
John Kessenich66011cb2018-03-06 16:12:04 -0700752 case glslang::EbvNumSubgroups:
753 builder.addCapability(spv::CapabilityGroupNonUniform);
754 return spv::BuiltInNumSubgroups;
755
756 case glslang::EbvSubgroupID:
757 builder.addCapability(spv::CapabilityGroupNonUniform);
758 return spv::BuiltInSubgroupId;
759
760 case glslang::EbvSubgroupSize2:
761 builder.addCapability(spv::CapabilityGroupNonUniform);
762 return spv::BuiltInSubgroupSize;
763
764 case glslang::EbvSubgroupInvocation2:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInSubgroupLocalInvocationId;
767
768 case glslang::EbvSubgroupEqMask2:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
771 return spv::BuiltInSubgroupEqMask;
772
773 case glslang::EbvSubgroupGeMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupGeMask;
777
778 case glslang::EbvSubgroupGtMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGtMask;
782
783 case glslang::EbvSubgroupLeMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupLeMask;
787
788 case glslang::EbvSubgroupLtMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800792#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800793 case glslang::EbvBaryCoordNoPersp:
794 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
795 return spv::BuiltInBaryCoordNoPerspAMD;
796
797 case glslang::EbvBaryCoordNoPerspCentroid:
798 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
799 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
800
801 case glslang::EbvBaryCoordNoPerspSample:
802 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
803 return spv::BuiltInBaryCoordNoPerspSampleAMD;
804
805 case glslang::EbvBaryCoordSmooth:
806 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
807 return spv::BuiltInBaryCoordSmoothAMD;
808
809 case glslang::EbvBaryCoordSmoothCentroid:
810 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
811 return spv::BuiltInBaryCoordSmoothCentroidAMD;
812
813 case glslang::EbvBaryCoordSmoothSample:
814 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
815 return spv::BuiltInBaryCoordSmoothSampleAMD;
816
817 case glslang::EbvBaryCoordPullModel:
818 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
819 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800820#endif
chaoc771d89f2017-01-13 01:10:53 -0800821
John Kessenich6c8aaac2017-02-27 01:20:51 -0700822 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700823 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700824 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700825 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826
827 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
chaoc771d89f2017-01-13 01:10:53 -0800832#ifdef NV_EXTENSIONS
833 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800834 if (!memberDeclaration) {
835 builder.addExtension(spv::E_SPV_NV_viewport_array2);
836 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
837 }
chaoc771d89f2017-01-13 01:10:53 -0800838 return spv::BuiltInViewportMaskNV;
839 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800840 if (!memberDeclaration) {
841 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
842 builder.addCapability(spv::CapabilityShaderStereoViewNV);
843 }
chaoc771d89f2017-01-13 01:10:53 -0800844 return spv::BuiltInSecondaryPositionNV;
845 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800846 if (!memberDeclaration) {
847 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
848 builder.addCapability(spv::CapabilityShaderStereoViewNV);
849 }
chaoc771d89f2017-01-13 01:10:53 -0800850 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800851 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800852 if (!memberDeclaration) {
853 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
854 builder.addCapability(spv::CapabilityPerViewAttributesNV);
855 }
chaocdf3956c2017-02-14 14:52:34 -0800856 return spv::BuiltInPositionPerViewNV;
857 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800858 if (!memberDeclaration) {
859 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
860 builder.addCapability(spv::CapabilityPerViewAttributesNV);
861 }
chaocdf3956c2017-02-14 14:52:34 -0800862 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700863 case glslang::EbvFragFullyCoveredNV:
864 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
865 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
866 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700867 case glslang::EbvFragmentSizeNV:
868 builder.addExtension(spv::E_SPV_NV_shading_rate);
869 builder.addCapability(spv::CapabilityShadingRateNV);
870 return spv::BuiltInFragmentSizeNV;
871 case glslang::EbvInvocationsPerPixelNV:
872 builder.addExtension(spv::E_SPV_NV_shading_rate);
873 builder.addCapability(spv::CapabilityShadingRateNV);
874 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700875
876 // raytracing
877 case glslang::EbvLaunchIdNV:
878 return spv::BuiltInLaunchIdNVX;
879 case glslang::EbvLaunchSizeNV:
880 return spv::BuiltInLaunchSizeNVX;
881 case glslang::EbvWorldRayOriginNV:
882 return spv::BuiltInWorldRayOriginNVX;
883 case glslang::EbvWorldRayDirectionNV:
884 return spv::BuiltInWorldRayDirectionNVX;
885 case glslang::EbvObjectRayOriginNV:
886 return spv::BuiltInObjectRayOriginNVX;
887 case glslang::EbvObjectRayDirectionNV:
888 return spv::BuiltInObjectRayDirectionNVX;
889 case glslang::EbvRayTminNV:
890 return spv::BuiltInRayTminNVX;
891 case glslang::EbvRayTmaxNV:
892 return spv::BuiltInRayTmaxNVX;
893 case glslang::EbvInstanceCustomIndexNV:
894 return spv::BuiltInInstanceCustomIndexNVX;
895 case glslang::EbvHitTNV:
896 return spv::BuiltInHitTNVX;
897 case glslang::EbvHitKindNV:
898 return spv::BuiltInHitKindNVX;
899 case glslang::EbvObjectToWorldNV:
900 return spv::BuiltInObjectToWorldNVX;
901 case glslang::EbvWorldToObjectNV:
902 return spv::BuiltInWorldToObjectNVX;
Chao Chen9eada4b2018-09-19 11:39:56 -0700903 case glslang::EbvBaryCoordNV:
904 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
905 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
906 return spv::BuiltInBaryCoordNV;
907 case glslang::EbvBaryCoordNoPerspNV:
908 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
909 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
910 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700911 case glslang::EbvTaskCountNV:
912 return spv::BuiltInTaskCountNV;
913 case glslang::EbvPrimitiveCountNV:
914 return spv::BuiltInPrimitiveCountNV;
915 case glslang::EbvPrimitiveIndicesNV:
916 return spv::BuiltInPrimitiveIndicesNV;
917 case glslang::EbvClipDistancePerViewNV:
918 return spv::BuiltInClipDistancePerViewNV;
919 case glslang::EbvCullDistancePerViewNV:
920 return spv::BuiltInCullDistancePerViewNV;
921 case glslang::EbvLayerPerViewNV:
922 return spv::BuiltInLayerPerViewNV;
923 case glslang::EbvMeshViewCountNV:
924 return spv::BuiltInMeshViewCountNV;
925 case glslang::EbvMeshViewIndicesNV:
926 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800927#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800928 default:
929 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600930 }
931}
932
Rex Xufc618912015-09-09 16:42:49 +0800933// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700934spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800935{
936 assert(type.getBasicType() == glslang::EbtSampler);
937
John Kessenich5d0fa972016-02-15 11:57:00 -0700938 // Check for capabilities
939 switch (type.getQualifier().layoutFormat) {
940 case glslang::ElfRg32f:
941 case glslang::ElfRg16f:
942 case glslang::ElfR11fG11fB10f:
943 case glslang::ElfR16f:
944 case glslang::ElfRgba16:
945 case glslang::ElfRgb10A2:
946 case glslang::ElfRg16:
947 case glslang::ElfRg8:
948 case glslang::ElfR16:
949 case glslang::ElfR8:
950 case glslang::ElfRgba16Snorm:
951 case glslang::ElfRg16Snorm:
952 case glslang::ElfRg8Snorm:
953 case glslang::ElfR16Snorm:
954 case glslang::ElfR8Snorm:
955
956 case glslang::ElfRg32i:
957 case glslang::ElfRg16i:
958 case glslang::ElfRg8i:
959 case glslang::ElfR16i:
960 case glslang::ElfR8i:
961
962 case glslang::ElfRgb10a2ui:
963 case glslang::ElfRg32ui:
964 case glslang::ElfRg16ui:
965 case glslang::ElfRg8ui:
966 case glslang::ElfR16ui:
967 case glslang::ElfR8ui:
968 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
969 break;
970
971 default:
972 break;
973 }
974
975 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800976 switch (type.getQualifier().layoutFormat) {
977 case glslang::ElfNone: return spv::ImageFormatUnknown;
978 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
979 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
980 case glslang::ElfR32f: return spv::ImageFormatR32f;
981 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
982 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
983 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
984 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
985 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
986 case glslang::ElfR16f: return spv::ImageFormatR16f;
987 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
988 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
989 case glslang::ElfRg16: return spv::ImageFormatRg16;
990 case glslang::ElfRg8: return spv::ImageFormatRg8;
991 case glslang::ElfR16: return spv::ImageFormatR16;
992 case glslang::ElfR8: return spv::ImageFormatR8;
993 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
994 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
995 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
996 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
997 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
998 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
999 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1000 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1001 case glslang::ElfR32i: return spv::ImageFormatR32i;
1002 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1003 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1004 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1005 case glslang::ElfR16i: return spv::ImageFormatR16i;
1006 case glslang::ElfR8i: return spv::ImageFormatR8i;
1007 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1008 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1009 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1010 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1011 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1012 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1013 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1014 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1015 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1016 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001017 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001018 }
1019}
1020
John Kesseniche18fd202018-01-30 11:01:39 -07001021spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001022{
John Kesseniche18fd202018-01-30 11:01:39 -07001023 if (selectionNode.getFlatten())
1024 return spv::SelectionControlFlattenMask;
1025 if (selectionNode.getDontFlatten())
1026 return spv::SelectionControlDontFlattenMask;
1027 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001028}
1029
John Kesseniche18fd202018-01-30 11:01:39 -07001030spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001031{
John Kesseniche18fd202018-01-30 11:01:39 -07001032 if (switchNode.getFlatten())
1033 return spv::SelectionControlFlattenMask;
1034 if (switchNode.getDontFlatten())
1035 return spv::SelectionControlDontFlattenMask;
1036 return spv::SelectionControlMaskNone;
1037}
1038
John Kessenicha2858d92018-01-31 08:11:18 -07001039// return a non-0 dependency if the dependency argument must be set
1040spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1041 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001042{
1043 spv::LoopControlMask control = spv::LoopControlMaskNone;
1044
1045 if (loopNode.getDontUnroll())
1046 control = control | spv::LoopControlDontUnrollMask;
1047 if (loopNode.getUnroll())
1048 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001049 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001050 control = control | spv::LoopControlDependencyInfiniteMask;
1051 else if (loopNode.getLoopDependency() > 0) {
1052 control = control | spv::LoopControlDependencyLengthMask;
1053 dependencyLength = loopNode.getLoopDependency();
1054 }
John Kesseniche18fd202018-01-30 11:01:39 -07001055
1056 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001057}
1058
John Kessenicha5c5fb62017-05-05 05:09:58 -06001059// Translate glslang type to SPIR-V storage class.
1060spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1061{
1062 if (type.getQualifier().isPipeInput())
1063 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001064 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001065 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001066
1067 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1068 type.getQualifier().storage == glslang::EvqUniform) {
1069 if (type.getBasicType() == glslang::EbtAtomicUint)
1070 return spv::StorageClassAtomicCounter;
1071 if (type.containsOpaque())
1072 return spv::StorageClassUniformConstant;
1073 }
1074
1075 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001076 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001077 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001078 }
1079
1080 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001081 if (type.getQualifier().layoutPushConstant)
1082 return spv::StorageClassPushConstant;
Chao Chenb50c02e2018-09-19 11:42:24 -07001083#ifdef NV_EXTENSIONS
1084 if (type.getQualifier().layoutShaderRecordNV)
1085 return spv::StorageClassShaderRecordBufferNVX;
1086#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001087 if (type.getBasicType() == glslang::EbtBlock)
1088 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001089 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001090 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001091
1092 switch (type.getQualifier().storage) {
1093 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1094 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1095 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1096 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001097#ifdef NV_EXTENSIONS
1098 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNVX;
1099 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNVX;
1100 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNVX;
1101#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001102 default:
1103 assert(0);
1104 break;
1105 }
1106
1107 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001108}
1109
John Kessenich5611c6d2018-04-05 11:25:02 -06001110// Add capabilities pertaining to how an array is indexed.
1111void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1112 const glslang::TType& indexType)
1113{
1114 if (indexType.getQualifier().isNonUniform()) {
1115 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001116 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001117 if (baseType.getBasicType() == glslang::EbtSampler) {
1118 if (baseType.getQualifier().hasAttachment())
1119 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1120 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1121 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1122 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1123 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1124 else if (baseType.isImage())
1125 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1126 else if (baseType.isTexture())
1127 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1128 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1129 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1130 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1131 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1132 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1133 }
1134 } else {
1135 // assume a dynamically uniform index
1136 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001137 if (baseType.getQualifier().hasAttachment()) {
1138 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001139 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001140 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1141 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001142 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001143 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1144 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001145 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001146 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001147 }
1148 }
1149}
1150
qining25262b32016-05-06 17:25:16 -04001151// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001152// descriptor set.
1153bool IsDescriptorResource(const glslang::TType& type)
1154{
John Kessenichf7497e22016-03-08 21:36:22 -07001155 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001156 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001157 return type.getQualifier().isUniformOrBuffer() &&
1158#ifdef NV_EXTENSIONS
1159 ! type.getQualifier().layoutShaderRecordNV &&
1160#endif
1161 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001162
1163 // non block...
1164 // basically samplerXXX/subpass/sampler/texture are all included
1165 // if they are the global-scope-class, not the function parameter
1166 // (or local, if they ever exist) class.
1167 if (type.getBasicType() == glslang::EbtSampler)
1168 return type.getQualifier().isUniformOrBuffer();
1169
1170 // None of the above.
1171 return false;
1172}
1173
John Kesseniche0b6cad2015-12-24 10:30:13 -07001174void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1175{
1176 if (child.layoutMatrix == glslang::ElmNone)
1177 child.layoutMatrix = parent.layoutMatrix;
1178
1179 if (parent.invariant)
1180 child.invariant = true;
1181 if (parent.nopersp)
1182 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001183#ifdef AMD_EXTENSIONS
1184 if (parent.explicitInterp)
1185 child.explicitInterp = true;
1186#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001187 if (parent.flat)
1188 child.flat = true;
1189 if (parent.centroid)
1190 child.centroid = true;
1191 if (parent.patch)
1192 child.patch = true;
1193 if (parent.sample)
1194 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001195 if (parent.coherent)
1196 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001197 if (parent.devicecoherent)
1198 child.devicecoherent = true;
1199 if (parent.queuefamilycoherent)
1200 child.queuefamilycoherent = true;
1201 if (parent.workgroupcoherent)
1202 child.workgroupcoherent = true;
1203 if (parent.subgroupcoherent)
1204 child.subgroupcoherent = true;
1205 if (parent.nonprivate)
1206 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001207 if (parent.volatil)
1208 child.volatil = true;
1209 if (parent.restrict)
1210 child.restrict = true;
1211 if (parent.readonly)
1212 child.readonly = true;
1213 if (parent.writeonly)
1214 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001215#ifdef NV_EXTENSIONS
1216 if (parent.perPrimitiveNV)
1217 child.perPrimitiveNV = true;
1218 if (parent.perViewNV)
1219 child.perViewNV = true;
1220 if (parent.perTaskNV)
1221 child.perTaskNV = true;
1222#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001223}
1224
John Kessenichf2b7f332016-09-01 17:05:23 -06001225bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001226{
John Kessenich7b9fa252016-01-21 18:56:57 -07001227 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001228 // - struct members might inherit from a struct declaration
1229 // (note that non-block structs don't explicitly inherit,
1230 // only implicitly, meaning no decoration involved)
1231 // - affect decorations on the struct members
1232 // (note smooth does not, and expecting something like volatile
1233 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001234 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001235 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001236}
1237
John Kessenich140f3df2015-06-26 16:58:36 -06001238//
1239// Implement the TGlslangToSpvTraverser class.
1240//
1241
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001242TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001243 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1244 : TIntermTraverser(true, false, true),
1245 options(options),
1246 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001247 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001248 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001249 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001250 glslangIntermediate(glslangIntermediate)
1251{
1252 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1253
1254 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001255 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1256 glslangIntermediate->getVersion());
1257
John Kessenich121853f2017-05-31 17:11:16 -06001258 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001259 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001260 builder.setSourceFile(glslangIntermediate->getSourceFile());
1261
1262 // Set the source shader's text. If for SPV version 1.0, include
1263 // a preamble in comments stating the OpModuleProcessed instructions.
1264 // Otherwise, emit those as actual instructions.
1265 std::string text;
1266 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1267 for (int p = 0; p < (int)processes.size(); ++p) {
1268 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1269 text.append("// OpModuleProcessed ");
1270 text.append(processes[p]);
1271 text.append("\n");
1272 } else
1273 builder.addModuleProcessed(processes[p]);
1274 }
1275 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1276 text.append("#line 1\n");
1277 text.append(glslangIntermediate->getSourceText());
1278 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001279 }
John Kessenich140f3df2015-06-26 16:58:36 -06001280 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001281 if (glslangIntermediate->usingVulkanMemoryModel()) {
1282 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1283 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1284 } else {
1285 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1286 }
John Kessenicheee9d532016-09-19 18:09:30 -06001287 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1288 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001289
1290 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001291 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1292 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001293 builder.addSourceExtension(it->c_str());
1294
1295 // Add the top-level modes for this shader.
1296
John Kessenich92187592016-02-01 13:45:25 -07001297 if (glslangIntermediate->getXfbMode()) {
1298 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001299 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001300 }
John Kessenich140f3df2015-06-26 16:58:36 -06001301
1302 unsigned int mode;
1303 switch (glslangIntermediate->getStage()) {
1304 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001305 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001306 break;
1307
steve-lunarge7412492017-03-23 11:56:07 -06001308 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001309 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001310 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001311
steve-lunarge7412492017-03-23 11:56:07 -06001312 glslang::TLayoutGeometry primitive;
1313
1314 if (glslangIntermediate->getStage() == EShLangTessControl) {
1315 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1316 primitive = glslangIntermediate->getOutputPrimitive();
1317 } else {
1318 primitive = glslangIntermediate->getInputPrimitive();
1319 }
1320
1321 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001322 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1323 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1324 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001325 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001326 }
John Kessenich4016e382016-07-15 11:53:56 -06001327 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001328 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1329
John Kesseniche6903322015-10-13 16:29:02 -06001330 switch (glslangIntermediate->getVertexSpacing()) {
1331 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1332 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1333 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001334 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001335 }
John Kessenich4016e382016-07-15 11:53:56 -06001336 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001337 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1338
1339 switch (glslangIntermediate->getVertexOrder()) {
1340 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1341 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001342 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001343 }
John Kessenich4016e382016-07-15 11:53:56 -06001344 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001345 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1346
1347 if (glslangIntermediate->getPointMode())
1348 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001349 break;
1350
1351 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001352 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001353 switch (glslangIntermediate->getInputPrimitive()) {
1354 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1355 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1356 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001357 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001358 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001359 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001360 }
John Kessenich4016e382016-07-15 11:53:56 -06001361 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001362 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001363
John Kessenich140f3df2015-06-26 16:58:36 -06001364 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1365
1366 switch (glslangIntermediate->getOutputPrimitive()) {
1367 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1368 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1369 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001370 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001371 }
John Kessenich4016e382016-07-15 11:53:56 -06001372 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001373 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1374 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1375 break;
1376
1377 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001378 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001379 if (glslangIntermediate->getPixelCenterInteger())
1380 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001381
John Kessenich140f3df2015-06-26 16:58:36 -06001382 if (glslangIntermediate->getOriginUpperLeft())
1383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001384 else
1385 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001386
1387 if (glslangIntermediate->getEarlyFragmentTests())
1388 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1389
chaocc1204522017-06-30 17:14:30 -07001390 if (glslangIntermediate->getPostDepthCoverage()) {
1391 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1392 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1393 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1394 }
1395
John Kesseniche6903322015-10-13 16:29:02 -06001396 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001397 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1398 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001399 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001400 }
John Kessenich4016e382016-07-15 11:53:56 -06001401 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001402 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1403
1404 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1405 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001406 break;
1407
1408 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001409 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001410 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1411 glslangIntermediate->getLocalSize(1),
1412 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001413#ifdef NV_EXTENSIONS
1414 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1415 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1416 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1417 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1418 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1419 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1421 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1422 }
1423#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001424 break;
1425
Chao Chen3c366992018-09-19 11:41:59 -07001426#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001427 case EShLangRayGenNV:
1428 case EShLangIntersectNV:
1429 case EShLangAnyHitNV:
1430 case EShLangClosestHitNV:
1431 case EShLangMissNV:
1432 case EShLangCallableNV:
1433 builder.addCapability(spv::CapabilityRaytracingNVX);
1434 builder.addExtension("SPV_NVX_raytracing");
1435 break;
Chao Chen3c366992018-09-19 11:41:59 -07001436 case EShLangTaskNV:
1437 case EShLangMeshNV:
1438 builder.addCapability(spv::CapabilityMeshShadingNV);
1439 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1441 glslangIntermediate->getLocalSize(1),
1442 glslangIntermediate->getLocalSize(2));
1443 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1446
1447 switch (glslangIntermediate->getOutputPrimitive()) {
1448 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1449 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1450 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1451 default: mode = spv::ExecutionModeMax; break;
1452 }
1453 if (mode != spv::ExecutionModeMax)
1454 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1455 }
1456 break;
1457#endif
1458
John Kessenich140f3df2015-06-26 16:58:36 -06001459 default:
1460 break;
1461 }
John Kessenich140f3df2015-06-26 16:58:36 -06001462}
1463
John Kessenichfca82622016-11-26 13:23:20 -07001464// Finish creating SPV, after the traversal is complete.
1465void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001466{
John Kessenichf04c51b2018-08-03 15:56:12 -06001467 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001468 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001469 builder.setBuildPoint(shaderEntry->getLastBlock());
1470 builder.leaveFunction();
1471 }
1472
John Kessenich7ba63412015-12-20 17:37:07 -07001473 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001474 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1475 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001476
John Kessenichf04c51b2018-08-03 15:56:12 -06001477 // Add capabilities, extensions, remove unneeded decorations, etc.,
1478 // based on the resulting SPIR-V.
1479 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001480}
1481
John Kessenichfca82622016-11-26 13:23:20 -07001482// Write the SPV into 'out'.
1483void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001484{
John Kessenichfca82622016-11-26 13:23:20 -07001485 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001486}
1487
1488//
1489// Implement the traversal functions.
1490//
1491// Return true from interior nodes to have the external traversal
1492// continue on to children. Return false if children were
1493// already processed.
1494//
1495
1496//
qining25262b32016-05-06 17:25:16 -04001497// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001498// - uniform/input reads
1499// - output writes
1500// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1501// - something simple that degenerates into the last bullet
1502//
1503void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1504{
qining75d1d802016-04-06 14:42:01 -04001505 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1506 if (symbol->getType().getQualifier().isSpecConstant())
1507 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1508
John Kessenich140f3df2015-06-26 16:58:36 -06001509 // getSymbolId() will set up all the IO decorations on the first call.
1510 // Formal function parameters were mapped during makeFunctions().
1511 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001512
1513 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1514 if (builder.isPointer(id)) {
1515 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001516 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1517 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1518 iOSet.insert(id);
1519 }
John Kessenich7ba63412015-12-20 17:37:07 -07001520 }
1521
1522 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001523 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001524 // Prepare to generate code for the access
1525
1526 // L-value chains will be computed left to right. We're on the symbol now,
1527 // which is the left-most part of the access chain, so now is "clear" time,
1528 // followed by setting the base.
1529 builder.clearAccessChain();
1530
1531 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001532 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001533 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001534 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001535 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001536 // These are also pure R-values.
1537 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001538 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001539 builder.setAccessChainRValue(id);
1540 else
1541 builder.setAccessChainLValue(id);
1542 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001543
1544 // Process linkage-only nodes for any special additional interface work.
1545 if (linkageOnly) {
1546 if (glslangIntermediate->getHlslFunctionality1()) {
1547 // Map implicit counter buffers to their originating buffers, which should have been
1548 // seen by now, given earlier pruning of unused counters, and preservation of order
1549 // of declaration.
1550 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1551 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1552 // Save possible originating buffers for counter buffers, keyed by
1553 // making the potential counter-buffer name.
1554 std::string keyName = symbol->getName().c_str();
1555 keyName = glslangIntermediate->addCounterBufferName(keyName);
1556 counterOriginator[keyName] = symbol;
1557 } else {
1558 // Handle a counter buffer, by finding the saved originating buffer.
1559 std::string keyName = symbol->getName().c_str();
1560 auto it = counterOriginator.find(keyName);
1561 if (it != counterOriginator.end()) {
1562 id = getSymbolId(it->second);
1563 if (id != spv::NoResult) {
1564 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001565 if (counterId != spv::NoResult) {
1566 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001567 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001568 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001569 }
1570 }
1571 }
1572 }
1573 }
1574 }
John Kessenich140f3df2015-06-26 16:58:36 -06001575}
1576
1577bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1578{
John Kesseniche485c7a2017-05-31 18:50:53 -06001579 builder.setLine(node->getLoc().line);
1580
qining40887662016-04-03 22:20:42 -04001581 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1582 if (node->getType().getQualifier().isSpecConstant())
1583 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1584
John Kessenich140f3df2015-06-26 16:58:36 -06001585 // First, handle special cases
1586 switch (node->getOp()) {
1587 case glslang::EOpAssign:
1588 case glslang::EOpAddAssign:
1589 case glslang::EOpSubAssign:
1590 case glslang::EOpMulAssign:
1591 case glslang::EOpVectorTimesMatrixAssign:
1592 case glslang::EOpVectorTimesScalarAssign:
1593 case glslang::EOpMatrixTimesScalarAssign:
1594 case glslang::EOpMatrixTimesMatrixAssign:
1595 case glslang::EOpDivAssign:
1596 case glslang::EOpModAssign:
1597 case glslang::EOpAndAssign:
1598 case glslang::EOpInclusiveOrAssign:
1599 case glslang::EOpExclusiveOrAssign:
1600 case glslang::EOpLeftShiftAssign:
1601 case glslang::EOpRightShiftAssign:
1602 // A bin-op assign "a += b" means the same thing as "a = a + b"
1603 // where a is evaluated before b. For a simple assignment, GLSL
1604 // says to evaluate the left before the right. So, always, left
1605 // node then right node.
1606 {
1607 // get the left l-value, save it away
1608 builder.clearAccessChain();
1609 node->getLeft()->traverse(this);
1610 spv::Builder::AccessChain lValue = builder.getAccessChain();
1611
1612 // evaluate the right
1613 builder.clearAccessChain();
1614 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001615 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001616
1617 if (node->getOp() != glslang::EOpAssign) {
1618 // the left is also an r-value
1619 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001620 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001623 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001624 TranslateNoContractionDecoration(node->getType().getQualifier()),
1625 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001626 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001627 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1628 node->getType().getBasicType());
1629
1630 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001631 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001632 }
1633
1634 // store the result
1635 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001636 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001637
1638 // assignments are expressions having an rValue after they are evaluated...
1639 builder.clearAccessChain();
1640 builder.setAccessChainRValue(rValue);
1641 }
1642 return false;
1643 case glslang::EOpIndexDirect:
1644 case glslang::EOpIndexDirectStruct:
1645 {
1646 // Get the left part of the access chain.
1647 node->getLeft()->traverse(this);
1648
1649 // Add the next element in the chain
1650
David Netoa901ffe2016-06-08 14:11:40 +01001651 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001652 if (! node->getLeft()->getType().isArray() &&
1653 node->getLeft()->getType().isVector() &&
1654 node->getOp() == glslang::EOpIndexDirect) {
1655 // This is essentially a hard-coded vector swizzle of size 1,
1656 // so short circuit the access-chain stuff with a swizzle.
1657 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001658 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001659 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001660 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001661 int spvIndex = glslangIndex;
1662 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1663 node->getOp() == glslang::EOpIndexDirectStruct)
1664 {
1665 // This may be, e.g., an anonymous block-member selection, which generally need
1666 // index remapping due to hidden members in anonymous blocks.
1667 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1668 assert(remapper.size() > 0);
1669 spvIndex = remapper[glslangIndex];
1670 }
John Kessenichebb50532016-05-16 19:22:05 -06001671
David Netoa901ffe2016-06-08 14:11:40 +01001672 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001673 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001674
1675 // Add capabilities here for accessing PointSize and clip/cull distance.
1676 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001677 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001678 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001679 }
1680 }
1681 return false;
1682 case glslang::EOpIndexIndirect:
1683 {
1684 // Structure or array or vector indirection.
1685 // Will use native SPIR-V access-chain for struct and array indirection;
1686 // matrices are arrays of vectors, so will also work for a matrix.
1687 // Will use the access chain's 'component' for variable index into a vector.
1688
1689 // This adapter is building access chains left to right.
1690 // Set up the access chain to the left.
1691 node->getLeft()->traverse(this);
1692
1693 // save it so that computing the right side doesn't trash it
1694 spv::Builder::AccessChain partial = builder.getAccessChain();
1695
1696 // compute the next index in the chain
1697 builder.clearAccessChain();
1698 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001699 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001700
John Kessenich5611c6d2018-04-05 11:25:02 -06001701 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1702
John Kessenich140f3df2015-06-26 16:58:36 -06001703 // restore the saved access chain
1704 builder.setAccessChain(partial);
1705
1706 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001707 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001708 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001709 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001710 }
1711 return false;
1712 case glslang::EOpVectorSwizzle:
1713 {
1714 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001715 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001716 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001717 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001718 }
1719 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001720 case glslang::EOpMatrixSwizzle:
1721 logger->missingFunctionality("matrix swizzle");
1722 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001723 case glslang::EOpLogicalOr:
1724 case glslang::EOpLogicalAnd:
1725 {
1726
1727 // These may require short circuiting, but can sometimes be done as straight
1728 // binary operations. The right operand must be short circuited if it has
1729 // side effects, and should probably be if it is complex.
1730 if (isTrivial(node->getRight()->getAsTyped()))
1731 break; // handle below as a normal binary operation
1732 // otherwise, we need to do dynamic short circuiting on the right operand
1733 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1734 builder.clearAccessChain();
1735 builder.setAccessChainRValue(result);
1736 }
1737 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001738 default:
1739 break;
1740 }
1741
1742 // Assume generic binary op...
1743
John Kessenich32cfd492016-02-02 12:37:46 -07001744 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001745 builder.clearAccessChain();
1746 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001747 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001748
John Kessenich32cfd492016-02-02 12:37:46 -07001749 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001750 builder.clearAccessChain();
1751 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001752 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001753
John Kessenich32cfd492016-02-02 12:37:46 -07001754 // get result
John Kessenichead86222018-03-28 18:01:20 -06001755 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001756 TranslateNoContractionDecoration(node->getType().getQualifier()),
1757 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001758 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001759 convertGlslangToSpvType(node->getType()), left, right,
1760 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001761
John Kessenich50e57562015-12-21 21:21:11 -07001762 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001763 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001764 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001765 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001766 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001767 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001768 return false;
1769 }
John Kessenich140f3df2015-06-26 16:58:36 -06001770}
1771
1772bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1773{
John Kesseniche485c7a2017-05-31 18:50:53 -06001774 builder.setLine(node->getLoc().line);
1775
qining40887662016-04-03 22:20:42 -04001776 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1777 if (node->getType().getQualifier().isSpecConstant())
1778 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1779
John Kessenichfc51d282015-08-19 13:34:18 -06001780 spv::Id result = spv::NoResult;
1781
1782 // try texturing first
1783 result = createImageTextureFunctionCall(node);
1784 if (result != spv::NoResult) {
1785 builder.clearAccessChain();
1786 builder.setAccessChainRValue(result);
1787
1788 return false; // done with this node
1789 }
1790
1791 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001792
1793 if (node->getOp() == glslang::EOpArrayLength) {
1794 // Quite special; won't want to evaluate the operand.
1795
John Kessenich5611c6d2018-04-05 11:25:02 -06001796 // Currently, the front-end does not allow .length() on an array until it is sized,
1797 // except for the last block membeor of an SSBO.
1798 // TODO: If this changes, link-time sized arrays might show up here, and need their
1799 // size extracted.
1800
John Kessenichc9a80832015-09-12 12:17:44 -06001801 // Normal .length() would have been constant folded by the front-end.
1802 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001803 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001804
John Kessenichc9a80832015-09-12 12:17:44 -06001805 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1806 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001807 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1808 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001809
1810 builder.clearAccessChain();
1811 builder.setAccessChainRValue(length);
1812
1813 return false;
1814 }
1815
John Kessenichfc51d282015-08-19 13:34:18 -06001816 // Start by evaluating the operand
1817
John Kessenich8c8505c2016-07-26 12:50:38 -06001818 // Does it need a swizzle inversion? If so, evaluation is inverted;
1819 // operate first on the swizzle base, then apply the swizzle.
1820 spv::Id invertedType = spv::NoType;
1821 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1822 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1823 invertedType = getInvertedSwizzleType(*node->getOperand());
1824
John Kessenich140f3df2015-06-26 16:58:36 -06001825 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001826 if (invertedType != spv::NoType)
1827 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1828 else
1829 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001830
Rex Xufc618912015-09-09 16:42:49 +08001831 spv::Id operand = spv::NoResult;
1832
1833 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1834 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001835 node->getOp() == glslang::EOpAtomicCounter ||
1836 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001837 operand = builder.accessChainGetLValue(); // Special case l-value operands
1838 else
John Kessenich32cfd492016-02-02 12:37:46 -07001839 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
John Kessenichead86222018-03-28 18:01:20 -06001841 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001842 TranslateNoContractionDecoration(node->getType().getQualifier()),
1843 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001846 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001847 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
1849 // if not, then possibly an operation
1850 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001851 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001852
1853 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001854 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001855 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001856 builder.addDecoration(result, decorations.nonUniform);
1857 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001858
John Kessenich140f3df2015-06-26 16:58:36 -06001859 builder.clearAccessChain();
1860 builder.setAccessChainRValue(result);
1861
1862 return false; // done with this node
1863 }
1864
1865 // it must be a special case, check...
1866 switch (node->getOp()) {
1867 case glslang::EOpPostIncrement:
1868 case glslang::EOpPostDecrement:
1869 case glslang::EOpPreIncrement:
1870 case glslang::EOpPreDecrement:
1871 {
1872 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001873 spv::Id one = 0;
1874 if (node->getBasicType() == glslang::EbtFloat)
1875 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001876 else if (node->getBasicType() == glslang::EbtDouble)
1877 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001878 else if (node->getBasicType() == glslang::EbtFloat16)
1879 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001880 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1881 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001882 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1883 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001884 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1885 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001886 else
1887 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001888 glslang::TOperator op;
1889 if (node->getOp() == glslang::EOpPreIncrement ||
1890 node->getOp() == glslang::EOpPostIncrement)
1891 op = glslang::EOpAdd;
1892 else
1893 op = glslang::EOpSub;
1894
John Kessenichead86222018-03-28 18:01:20 -06001895 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001896 convertGlslangToSpvType(node->getType()), operand, one,
1897 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001898 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001899
1900 // The result of operation is always stored, but conditionally the
1901 // consumed result. The consumed result is always an r-value.
1902 builder.accessChainStore(result);
1903 builder.clearAccessChain();
1904 if (node->getOp() == glslang::EOpPreIncrement ||
1905 node->getOp() == glslang::EOpPreDecrement)
1906 builder.setAccessChainRValue(result);
1907 else
1908 builder.setAccessChainRValue(operand);
1909 }
1910
1911 return false;
1912
1913 case glslang::EOpEmitStreamVertex:
1914 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1915 return false;
1916 case glslang::EOpEndStreamPrimitive:
1917 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1918 return false;
1919
1920 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001921 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001922 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001923 }
John Kessenich140f3df2015-06-26 16:58:36 -06001924}
1925
1926bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1927{
qining27e04a02016-04-14 16:40:20 -04001928 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1929 if (node->getType().getQualifier().isSpecConstant())
1930 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1931
John Kessenichfc51d282015-08-19 13:34:18 -06001932 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001933 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1934 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001935
1936 // try texturing
1937 result = createImageTextureFunctionCall(node);
1938 if (result != spv::NoResult) {
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(result);
1941
1942 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001943 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001944#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001945 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001946#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001947 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001948 // "imageStore" is a special case, which has no result
1949 return false;
1950 }
John Kessenichfc51d282015-08-19 13:34:18 -06001951
John Kessenich140f3df2015-06-26 16:58:36 -06001952 glslang::TOperator binOp = glslang::EOpNull;
1953 bool reduceComparison = true;
1954 bool isMatrix = false;
1955 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001956 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001957
1958 assert(node->getOp());
1959
John Kessenichf6640762016-08-01 19:44:00 -06001960 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001961
1962 switch (node->getOp()) {
1963 case glslang::EOpSequence:
1964 {
1965 if (preVisit)
1966 ++sequenceDepth;
1967 else
1968 --sequenceDepth;
1969
1970 if (sequenceDepth == 1) {
1971 // If this is the parent node of all the functions, we want to see them
1972 // early, so all call points have actual SPIR-V functions to reference.
1973 // In all cases, still let the traverser visit the children for us.
1974 makeFunctions(node->getAsAggregate()->getSequence());
1975
John Kessenich6fccb3c2016-09-19 16:01:41 -06001976 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001977 // anything else gets there, so visit out of order, doing them all now.
1978 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1979
John Kessenich6a60c2f2016-12-08 21:01:59 -07001980 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001981 // so do them manually.
1982 visitFunctions(node->getAsAggregate()->getSequence());
1983
1984 return false;
1985 }
1986
1987 return true;
1988 }
1989 case glslang::EOpLinkerObjects:
1990 {
1991 if (visit == glslang::EvPreVisit)
1992 linkageOnly = true;
1993 else
1994 linkageOnly = false;
1995
1996 return true;
1997 }
1998 case glslang::EOpComma:
1999 {
2000 // processing from left to right naturally leaves the right-most
2001 // lying around in the access chain
2002 glslang::TIntermSequence& glslangOperands = node->getSequence();
2003 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2004 glslangOperands[i]->traverse(this);
2005
2006 return false;
2007 }
2008 case glslang::EOpFunction:
2009 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002010 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002011 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002012 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002013 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002014 } else {
2015 handleFunctionEntry(node);
2016 }
2017 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002018 if (inEntryPoint)
2019 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002020 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002021 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002022 }
2023
2024 return true;
2025 case glslang::EOpParameters:
2026 // Parameters will have been consumed by EOpFunction processing, but not
2027 // the body, so we still visited the function node's children, making this
2028 // child redundant.
2029 return false;
2030 case glslang::EOpFunctionCall:
2031 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002032 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002033 if (node->isUserDefined())
2034 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002035 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002036 if (result) {
2037 builder.clearAccessChain();
2038 builder.setAccessChainRValue(result);
2039 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002040 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002041
2042 return false;
2043 }
2044 case glslang::EOpConstructMat2x2:
2045 case glslang::EOpConstructMat2x3:
2046 case glslang::EOpConstructMat2x4:
2047 case glslang::EOpConstructMat3x2:
2048 case glslang::EOpConstructMat3x3:
2049 case glslang::EOpConstructMat3x4:
2050 case glslang::EOpConstructMat4x2:
2051 case glslang::EOpConstructMat4x3:
2052 case glslang::EOpConstructMat4x4:
2053 case glslang::EOpConstructDMat2x2:
2054 case glslang::EOpConstructDMat2x3:
2055 case glslang::EOpConstructDMat2x4:
2056 case glslang::EOpConstructDMat3x2:
2057 case glslang::EOpConstructDMat3x3:
2058 case glslang::EOpConstructDMat3x4:
2059 case glslang::EOpConstructDMat4x2:
2060 case glslang::EOpConstructDMat4x3:
2061 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002062 case glslang::EOpConstructIMat2x2:
2063 case glslang::EOpConstructIMat2x3:
2064 case glslang::EOpConstructIMat2x4:
2065 case glslang::EOpConstructIMat3x2:
2066 case glslang::EOpConstructIMat3x3:
2067 case glslang::EOpConstructIMat3x4:
2068 case glslang::EOpConstructIMat4x2:
2069 case glslang::EOpConstructIMat4x3:
2070 case glslang::EOpConstructIMat4x4:
2071 case glslang::EOpConstructUMat2x2:
2072 case glslang::EOpConstructUMat2x3:
2073 case glslang::EOpConstructUMat2x4:
2074 case glslang::EOpConstructUMat3x2:
2075 case glslang::EOpConstructUMat3x3:
2076 case glslang::EOpConstructUMat3x4:
2077 case glslang::EOpConstructUMat4x2:
2078 case glslang::EOpConstructUMat4x3:
2079 case glslang::EOpConstructUMat4x4:
2080 case glslang::EOpConstructBMat2x2:
2081 case glslang::EOpConstructBMat2x3:
2082 case glslang::EOpConstructBMat2x4:
2083 case glslang::EOpConstructBMat3x2:
2084 case glslang::EOpConstructBMat3x3:
2085 case glslang::EOpConstructBMat3x4:
2086 case glslang::EOpConstructBMat4x2:
2087 case glslang::EOpConstructBMat4x3:
2088 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002089 case glslang::EOpConstructF16Mat2x2:
2090 case glslang::EOpConstructF16Mat2x3:
2091 case glslang::EOpConstructF16Mat2x4:
2092 case glslang::EOpConstructF16Mat3x2:
2093 case glslang::EOpConstructF16Mat3x3:
2094 case glslang::EOpConstructF16Mat3x4:
2095 case glslang::EOpConstructF16Mat4x2:
2096 case glslang::EOpConstructF16Mat4x3:
2097 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002098 isMatrix = true;
2099 // fall through
2100 case glslang::EOpConstructFloat:
2101 case glslang::EOpConstructVec2:
2102 case glslang::EOpConstructVec3:
2103 case glslang::EOpConstructVec4:
2104 case glslang::EOpConstructDouble:
2105 case glslang::EOpConstructDVec2:
2106 case glslang::EOpConstructDVec3:
2107 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002108 case glslang::EOpConstructFloat16:
2109 case glslang::EOpConstructF16Vec2:
2110 case glslang::EOpConstructF16Vec3:
2111 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002112 case glslang::EOpConstructBool:
2113 case glslang::EOpConstructBVec2:
2114 case glslang::EOpConstructBVec3:
2115 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002116 case glslang::EOpConstructInt8:
2117 case glslang::EOpConstructI8Vec2:
2118 case glslang::EOpConstructI8Vec3:
2119 case glslang::EOpConstructI8Vec4:
2120 case glslang::EOpConstructUint8:
2121 case glslang::EOpConstructU8Vec2:
2122 case glslang::EOpConstructU8Vec3:
2123 case glslang::EOpConstructU8Vec4:
2124 case glslang::EOpConstructInt16:
2125 case glslang::EOpConstructI16Vec2:
2126 case glslang::EOpConstructI16Vec3:
2127 case glslang::EOpConstructI16Vec4:
2128 case glslang::EOpConstructUint16:
2129 case glslang::EOpConstructU16Vec2:
2130 case glslang::EOpConstructU16Vec3:
2131 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002132 case glslang::EOpConstructInt:
2133 case glslang::EOpConstructIVec2:
2134 case glslang::EOpConstructIVec3:
2135 case glslang::EOpConstructIVec4:
2136 case glslang::EOpConstructUint:
2137 case glslang::EOpConstructUVec2:
2138 case glslang::EOpConstructUVec3:
2139 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002140 case glslang::EOpConstructInt64:
2141 case glslang::EOpConstructI64Vec2:
2142 case glslang::EOpConstructI64Vec3:
2143 case glslang::EOpConstructI64Vec4:
2144 case glslang::EOpConstructUint64:
2145 case glslang::EOpConstructU64Vec2:
2146 case glslang::EOpConstructU64Vec3:
2147 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002148 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002149 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002151 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002152 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002153 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002154 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002155 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002156 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002157 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002158 std::vector<spv::Id> constituents;
2159 for (int c = 0; c < (int)arguments.size(); ++c)
2160 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002161 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002162 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002163 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002164 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002165 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002166
2167 builder.clearAccessChain();
2168 builder.setAccessChainRValue(constructed);
2169
2170 return false;
2171 }
2172
2173 // These six are component-wise compares with component-wise results.
2174 // Forward on to createBinaryOperation(), requesting a vector result.
2175 case glslang::EOpLessThan:
2176 case glslang::EOpGreaterThan:
2177 case glslang::EOpLessThanEqual:
2178 case glslang::EOpGreaterThanEqual:
2179 case glslang::EOpVectorEqual:
2180 case glslang::EOpVectorNotEqual:
2181 {
2182 // Map the operation to a binary
2183 binOp = node->getOp();
2184 reduceComparison = false;
2185 switch (node->getOp()) {
2186 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2187 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2188 default: binOp = node->getOp(); break;
2189 }
2190
2191 break;
2192 }
2193 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002194 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002195 binOp = glslang::EOpMul;
2196 break;
2197 case glslang::EOpOuterProduct:
2198 // two vectors multiplied to make a matrix
2199 binOp = glslang::EOpOuterProduct;
2200 break;
2201 case glslang::EOpDot:
2202 {
qining25262b32016-05-06 17:25:16 -04002203 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002204 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002205 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002206 binOp = glslang::EOpMul;
2207 break;
2208 }
2209 case glslang::EOpMod:
2210 // when an aggregate, this is the floating-point mod built-in function,
2211 // which can be emitted by the one in createBinaryOperation()
2212 binOp = glslang::EOpMod;
2213 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002214 case glslang::EOpEmitVertex:
2215 case glslang::EOpEndPrimitive:
2216 case glslang::EOpBarrier:
2217 case glslang::EOpMemoryBarrier:
2218 case glslang::EOpMemoryBarrierAtomicCounter:
2219 case glslang::EOpMemoryBarrierBuffer:
2220 case glslang::EOpMemoryBarrierImage:
2221 case glslang::EOpMemoryBarrierShared:
2222 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002223 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002224 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002225 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002226 case glslang::EOpWorkgroupMemoryBarrier:
2227 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002228 case glslang::EOpSubgroupBarrier:
2229 case glslang::EOpSubgroupMemoryBarrier:
2230 case glslang::EOpSubgroupMemoryBarrierBuffer:
2231 case glslang::EOpSubgroupMemoryBarrierImage:
2232 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002233 noReturnValue = true;
2234 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2235 break;
2236
Jeff Bolz36831c92018-09-05 10:11:41 -05002237 case glslang::EOpAtomicStore:
2238 noReturnValue = true;
2239 // fallthrough
2240 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002241 case glslang::EOpAtomicAdd:
2242 case glslang::EOpAtomicMin:
2243 case glslang::EOpAtomicMax:
2244 case glslang::EOpAtomicAnd:
2245 case glslang::EOpAtomicOr:
2246 case glslang::EOpAtomicXor:
2247 case glslang::EOpAtomicExchange:
2248 case glslang::EOpAtomicCompSwap:
2249 atomic = true;
2250 break;
2251
John Kessenich0d0c6d32017-07-23 16:08:26 -06002252 case glslang::EOpAtomicCounterAdd:
2253 case glslang::EOpAtomicCounterSubtract:
2254 case glslang::EOpAtomicCounterMin:
2255 case glslang::EOpAtomicCounterMax:
2256 case glslang::EOpAtomicCounterAnd:
2257 case glslang::EOpAtomicCounterOr:
2258 case glslang::EOpAtomicCounterXor:
2259 case glslang::EOpAtomicCounterExchange:
2260 case glslang::EOpAtomicCounterCompSwap:
2261 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2262 builder.addCapability(spv::CapabilityAtomicStorageOps);
2263 atomic = true;
2264 break;
2265
Chao Chen3c366992018-09-19 11:41:59 -07002266#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002267 case glslang::EOpIgnoreIntersectionNV:
2268 case glslang::EOpTerminateRayNV:
2269 case glslang::EOpTraceNV:
Chao Chen3c366992018-09-19 11:41:59 -07002270 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2271 noReturnValue = true;
2272 break;
2273#endif
2274
John Kessenich140f3df2015-06-26 16:58:36 -06002275 default:
2276 break;
2277 }
2278
2279 //
2280 // See if it maps to a regular operation.
2281 //
John Kessenich140f3df2015-06-26 16:58:36 -06002282 if (binOp != glslang::EOpNull) {
2283 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2284 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2285 assert(left && right);
2286
2287 builder.clearAccessChain();
2288 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002289 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002290
2291 builder.clearAccessChain();
2292 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002293 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
John Kesseniche485c7a2017-05-31 18:50:53 -06002295 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002296 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002297 TranslateNoContractionDecoration(node->getType().getQualifier()),
2298 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002299 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002300 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002301 left->getType().getBasicType(), reduceComparison);
2302
2303 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002304 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002305 builder.clearAccessChain();
2306 builder.setAccessChainRValue(result);
2307
2308 return false;
2309 }
2310
John Kessenich426394d2015-07-23 10:22:48 -06002311 //
2312 // Create the list of operands.
2313 //
John Kessenich140f3df2015-06-26 16:58:36 -06002314 glslang::TIntermSequence& glslangOperands = node->getSequence();
2315 std::vector<spv::Id> operands;
2316 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002317 // special case l-value operands; there are just a few
2318 bool lvalue = false;
2319 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002320 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002321 case glslang::EOpModf:
2322 if (arg == 1)
2323 lvalue = true;
2324 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002325 case glslang::EOpInterpolateAtSample:
2326 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002327#ifdef AMD_EXTENSIONS
2328 case glslang::EOpInterpolateAtVertex:
2329#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002330 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002331 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002332
2333 // Does it need a swizzle inversion? If so, evaluation is inverted;
2334 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002335 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002336 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2337 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2338 }
Rex Xu7a26c172015-12-08 17:12:09 +08002339 break;
Rex Xud4782c12015-09-06 16:30:11 +08002340 case glslang::EOpAtomicAdd:
2341 case glslang::EOpAtomicMin:
2342 case glslang::EOpAtomicMax:
2343 case glslang::EOpAtomicAnd:
2344 case glslang::EOpAtomicOr:
2345 case glslang::EOpAtomicXor:
2346 case glslang::EOpAtomicExchange:
2347 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002348 case glslang::EOpAtomicLoad:
2349 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002350 case glslang::EOpAtomicCounterAdd:
2351 case glslang::EOpAtomicCounterSubtract:
2352 case glslang::EOpAtomicCounterMin:
2353 case glslang::EOpAtomicCounterMax:
2354 case glslang::EOpAtomicCounterAnd:
2355 case glslang::EOpAtomicCounterOr:
2356 case glslang::EOpAtomicCounterXor:
2357 case glslang::EOpAtomicCounterExchange:
2358 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002359 if (arg == 0)
2360 lvalue = true;
2361 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002362 case glslang::EOpAddCarry:
2363 case glslang::EOpSubBorrow:
2364 if (arg == 2)
2365 lvalue = true;
2366 break;
2367 case glslang::EOpUMulExtended:
2368 case glslang::EOpIMulExtended:
2369 if (arg >= 2)
2370 lvalue = true;
2371 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 default:
2373 break;
2374 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002375 builder.clearAccessChain();
2376 if (invertedType != spv::NoType && arg == 0)
2377 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2378 else
2379 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002380 if (lvalue)
2381 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002382 else {
2383 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002384 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002385 }
John Kessenich140f3df2015-06-26 16:58:36 -06002386 }
John Kessenich426394d2015-07-23 10:22:48 -06002387
John Kesseniche485c7a2017-05-31 18:50:53 -06002388 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002389 if (atomic) {
2390 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002391 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002392 } else {
2393 // Pass through to generic operations.
2394 switch (glslangOperands.size()) {
2395 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002396 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002397 break;
2398 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002399 {
2400 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002401 TranslateNoContractionDecoration(node->getType().getQualifier()),
2402 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002403 result = createUnaryOperation(
2404 node->getOp(), decorations,
2405 resultType(), operands.front(),
2406 glslangOperands[0]->getAsTyped()->getBasicType());
2407 }
John Kessenich426394d2015-07-23 10:22:48 -06002408 break;
2409 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002410 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002411 break;
2412 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002413 if (invertedType)
2414 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002415 }
2416
2417 if (noReturnValue)
2418 return false;
2419
2420 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002421 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002422 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002423 } else {
2424 builder.clearAccessChain();
2425 builder.setAccessChainRValue(result);
2426 return false;
2427 }
2428}
2429
John Kessenich433e9ff2017-01-26 20:31:11 -07002430// This path handles both if-then-else and ?:
2431// The if-then-else has a node type of void, while
2432// ?: has either a void or a non-void node type
2433//
2434// Leaving the result, when not void:
2435// GLSL only has r-values as the result of a :?, but
2436// if we have an l-value, that can be more efficient if it will
2437// become the base of a complex r-value expression, because the
2438// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002439bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2440{
John Kessenich4bee5312018-02-20 21:29:05 -07002441 // See if it simple and safe, or required, to execute both sides.
2442 // Crucially, side effects must be either semantically required or avoided,
2443 // and there are performance trade-offs.
2444 // Return true if required or a good idea (and safe) to execute both sides,
2445 // false otherwise.
2446 const auto bothSidesPolicy = [&]() -> bool {
2447 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002448 if (node->getTrueBlock() == nullptr ||
2449 node->getFalseBlock() == nullptr)
2450 return false;
2451
John Kessenich4bee5312018-02-20 21:29:05 -07002452 // required? (unless we write additional code to look for side effects
2453 // and make performance trade-offs if none are present)
2454 if (!node->getShortCircuit())
2455 return true;
2456
2457 // if not required to execute both, decide based on performance/practicality...
2458
2459 // see if OpSelect can handle it
2460 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2461 node->getBasicType() == glslang::EbtVoid)
2462 return false;
2463
John Kessenich433e9ff2017-01-26 20:31:11 -07002464 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2465 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2466
2467 // return true if a single operand to ? : is okay for OpSelect
2468 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002469 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002470 };
2471
2472 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2473 operandOkay(node->getFalseBlock()->getAsTyped());
2474 };
2475
John Kessenich4bee5312018-02-20 21:29:05 -07002476 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2477 // emit the condition before doing anything with selection
2478 node->getCondition()->traverse(this);
2479 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2480
2481 // Find a way of executing both sides and selecting the right result.
2482 const auto executeBothSides = [&]() -> void {
2483 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002484 node->getTrueBlock()->traverse(this);
2485 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2486 node->getFalseBlock()->traverse(this);
2487 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2488
John Kesseniche485c7a2017-05-31 18:50:53 -06002489 builder.setLine(node->getLoc().line);
2490
John Kessenich4bee5312018-02-20 21:29:05 -07002491 // done if void
2492 if (node->getBasicType() == glslang::EbtVoid)
2493 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002494
John Kessenich4bee5312018-02-20 21:29:05 -07002495 // emit code to select between trueValue and falseValue
2496
2497 // see if OpSelect can handle it
2498 if (node->getType().isScalar() || node->getType().isVector()) {
2499 // Emit OpSelect for this selection.
2500
2501 // smear condition to vector, if necessary (AST is always scalar)
2502 if (builder.isVector(trueValue))
2503 condition = builder.smearScalar(spv::NoPrecision, condition,
2504 builder.makeVectorType(builder.makeBoolType(),
2505 builder.getNumComponents(trueValue)));
2506
2507 // OpSelect
2508 result = builder.createTriOp(spv::OpSelect,
2509 convertGlslangToSpvType(node->getType()), condition,
2510 trueValue, falseValue);
2511
2512 builder.clearAccessChain();
2513 builder.setAccessChainRValue(result);
2514 } else {
2515 // We need control flow to select the result.
2516 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2517 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2518
2519 // Selection control:
2520 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2521
2522 // make an "if" based on the value created by the condition
2523 spv::Builder::If ifBuilder(condition, control, builder);
2524
2525 // emit the "then" statement
2526 builder.createStore(trueValue, result);
2527 ifBuilder.makeBeginElse();
2528 // emit the "else" statement
2529 builder.createStore(falseValue, result);
2530
2531 // finish off the control flow
2532 ifBuilder.makeEndIf();
2533
2534 builder.clearAccessChain();
2535 builder.setAccessChainLValue(result);
2536 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002537 };
2538
John Kessenich4bee5312018-02-20 21:29:05 -07002539 // Execute the one side needed, as per the condition
2540 const auto executeOneSide = [&]() {
2541 // Always emit control flow.
2542 if (node->getBasicType() != glslang::EbtVoid)
2543 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002544
John Kessenich4bee5312018-02-20 21:29:05 -07002545 // Selection control:
2546 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2547
2548 // make an "if" based on the value created by the condition
2549 spv::Builder::If ifBuilder(condition, control, builder);
2550
2551 // emit the "then" statement
2552 if (node->getTrueBlock() != nullptr) {
2553 node->getTrueBlock()->traverse(this);
2554 if (result != spv::NoResult)
2555 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2556 }
2557
2558 if (node->getFalseBlock() != nullptr) {
2559 ifBuilder.makeBeginElse();
2560 // emit the "else" statement
2561 node->getFalseBlock()->traverse(this);
2562 if (result != spv::NoResult)
2563 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2564 }
2565
2566 // finish off the control flow
2567 ifBuilder.makeEndIf();
2568
2569 if (result != spv::NoResult) {
2570 builder.clearAccessChain();
2571 builder.setAccessChainLValue(result);
2572 }
2573 };
2574
2575 // Try for OpSelect (or a requirement to execute both sides)
2576 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002577 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2578 if (node->getType().getQualifier().isSpecConstant())
2579 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002580 executeBothSides();
2581 } else
2582 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002583
2584 return false;
2585}
2586
2587bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2588{
2589 // emit and get the condition before doing anything with switch
2590 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002591 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002592
Rex Xu57e65922017-07-04 23:23:40 +08002593 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002594 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002595
John Kessenich140f3df2015-06-26 16:58:36 -06002596 // browse the children to sort out code segments
2597 int defaultSegment = -1;
2598 std::vector<TIntermNode*> codeSegments;
2599 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2600 std::vector<int> caseValues;
2601 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2602 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2603 TIntermNode* child = *c;
2604 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002605 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002606 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002607 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002608 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2609 } else
2610 codeSegments.push_back(child);
2611 }
2612
qining25262b32016-05-06 17:25:16 -04002613 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002614 // statements between the last case and the end of the switch statement
2615 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2616 (int)codeSegments.size() == defaultSegment)
2617 codeSegments.push_back(nullptr);
2618
2619 // make the switch statement
2620 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002621 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002622
2623 // emit all the code in the segments
2624 breakForLoop.push(false);
2625 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2626 builder.nextSwitchSegment(segmentBlocks, s);
2627 if (codeSegments[s])
2628 codeSegments[s]->traverse(this);
2629 else
2630 builder.addSwitchBreak();
2631 }
2632 breakForLoop.pop();
2633
2634 builder.endSwitch(segmentBlocks);
2635
2636 return false;
2637}
2638
2639void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2640{
2641 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002642 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002643
2644 builder.clearAccessChain();
2645 builder.setAccessChainRValue(constant);
2646}
2647
2648bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2649{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002650 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002651 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002652
2653 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002654 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2655 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002656
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002657 // Spec requires back edges to target header blocks, and every header block
2658 // must dominate its merge block. Make a header block first to ensure these
2659 // conditions are met. By definition, it will contain OpLoopMerge, followed
2660 // by a block-ending branch. But we don't want to put any other body/test
2661 // instructions in it, since the body/test may have arbitrary instructions,
2662 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002663 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002664 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002665 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002666 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002667 spv::Block& test = builder.makeNewBlock();
2668 builder.createBranch(&test);
2669
2670 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002671 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002672 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002673 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2674
2675 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002676 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002677 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002678 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002679 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002680 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002681
2682 builder.setBuildPoint(&blocks.continue_target);
2683 if (node->getTerminal())
2684 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002685 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002686 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002687 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002688 builder.createBranch(&blocks.body);
2689
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002690 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002691 builder.setBuildPoint(&blocks.body);
2692 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002693 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002694 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002695 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002696
2697 builder.setBuildPoint(&blocks.continue_target);
2698 if (node->getTerminal())
2699 node->getTerminal()->traverse(this);
2700 if (node->getTest()) {
2701 node->getTest()->traverse(this);
2702 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002703 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002704 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002705 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002706 // TODO: unless there was a break/return/discard instruction
2707 // somewhere in the body, this is an infinite loop, so we should
2708 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002709 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002710 }
John Kessenich140f3df2015-06-26 16:58:36 -06002711 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002712 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002713 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002714 return false;
2715}
2716
2717bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2718{
2719 if (node->getExpression())
2720 node->getExpression()->traverse(this);
2721
John Kesseniche485c7a2017-05-31 18:50:53 -06002722 builder.setLine(node->getLoc().line);
2723
John Kessenich140f3df2015-06-26 16:58:36 -06002724 switch (node->getFlowOp()) {
2725 case glslang::EOpKill:
2726 builder.makeDiscard();
2727 break;
2728 case glslang::EOpBreak:
2729 if (breakForLoop.top())
2730 builder.createLoopExit();
2731 else
2732 builder.addSwitchBreak();
2733 break;
2734 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002735 builder.createLoopContinue();
2736 break;
2737 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002738 if (node->getExpression()) {
2739 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2740 spv::Id returnId = accessChainLoad(glslangReturnType);
2741 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2742 builder.clearAccessChain();
2743 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2744 builder.setAccessChainLValue(copyId);
2745 multiTypeStore(glslangReturnType, returnId);
2746 returnId = builder.createLoad(copyId);
2747 }
2748 builder.makeReturn(false, returnId);
2749 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002750 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002751
2752 builder.clearAccessChain();
2753 break;
2754
2755 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002756 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002757 break;
2758 }
2759
2760 return false;
2761}
2762
2763spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2764{
qining25262b32016-05-06 17:25:16 -04002765 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002766 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002767 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002768 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002769 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002770 }
2771
2772 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002773 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002774 spv::Id spvType = convertGlslangToSpvType(node->getType());
2775
Rex Xucabbb782017-03-24 13:41:14 +08002776 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2777 node->getType().containsBasicType(glslang::EbtInt16) ||
2778 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002779 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002780 switch (storageClass) {
2781 case spv::StorageClassInput:
2782 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002783 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002784 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002785 break;
2786 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002787 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002788 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002789 break;
2790 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002791 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002792 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2793 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002794 else
2795 builder.addCapability(spv::CapabilityStorageUniform16);
2796 break;
2797 case spv::StorageClassStorageBuffer:
2798 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2799 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2800 break;
2801 default:
2802 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002803 }
2804 }
Rex Xuf89ad982017-04-07 23:22:33 +08002805
John Kessenich312dcfb2018-07-03 13:19:51 -06002806 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2807 node->getType().containsBasicType(glslang::EbtUint8);
2808 if (contains8BitType) {
2809 if (storageClass == spv::StorageClassPushConstant) {
2810 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2811 builder.addCapability(spv::CapabilityStoragePushConstant8);
2812 } else if (storageClass == spv::StorageClassUniform) {
2813 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2814 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002815 } else if (storageClass == spv::StorageClassStorageBuffer) {
2816 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2817 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002818 }
2819 }
2820
John Kessenich140f3df2015-06-26 16:58:36 -06002821 const char* name = node->getName().c_str();
2822 if (glslang::IsAnonymous(name))
2823 name = "";
2824
2825 return builder.createVariable(storageClass, spvType, name);
2826}
2827
2828// Return type Id of the sampled type.
2829spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2830{
2831 switch (sampler.type) {
2832 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002833#ifdef AMD_EXTENSIONS
2834 case glslang::EbtFloat16:
2835 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2836 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2837 return builder.makeFloatType(16);
2838#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002839 case glslang::EbtInt: return builder.makeIntType(32);
2840 case glslang::EbtUint: return builder.makeUintType(32);
2841 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002842 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002843 return builder.makeFloatType(32);
2844 }
2845}
2846
John Kessenich8c8505c2016-07-26 12:50:38 -06002847// If node is a swizzle operation, return the type that should be used if
2848// the swizzle base is first consumed by another operation, before the swizzle
2849// is applied.
2850spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2851{
John Kessenichecba76f2017-01-06 00:34:48 -07002852 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002853 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2854 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2855 else
2856 return spv::NoType;
2857}
2858
2859// When inverting a swizzle with a parent op, this function
2860// will apply the swizzle operation to a completed parent operation.
2861spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2862{
2863 std::vector<unsigned> swizzle;
2864 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2865 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2866}
2867
John Kessenich8c8505c2016-07-26 12:50:38 -06002868// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2869void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2870{
2871 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2872 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2873 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2874}
2875
John Kessenich3ac051e2015-12-20 11:29:16 -07002876// Convert from a glslang type to an SPV type, by calling into a
2877// recursive version of this function. This establishes the inherited
2878// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002879spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2880{
John Kessenichead86222018-03-28 18:01:20 -06002881 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002882}
2883
2884// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002885// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002886// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002887spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2888 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002889{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002890 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002891
2892 switch (type.getBasicType()) {
2893 case glslang::EbtVoid:
2894 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002895 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002896 break;
2897 case glslang::EbtFloat:
2898 spvType = builder.makeFloatType(32);
2899 break;
2900 case glslang::EbtDouble:
2901 spvType = builder.makeFloatType(64);
2902 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002903 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002904 spvType = builder.makeFloatType(16);
2905 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002906 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002907 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2908 // a 32-bit int where non-0 means true.
2909 if (explicitLayout != glslang::ElpNone)
2910 spvType = builder.makeUintType(32);
2911 else
2912 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002913 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002914 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002915 spvType = builder.makeIntType(8);
2916 break;
2917 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002918 spvType = builder.makeUintType(8);
2919 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002920 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002921 spvType = builder.makeIntType(16);
2922 break;
2923 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002924 spvType = builder.makeUintType(16);
2925 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002926 case glslang::EbtInt:
2927 spvType = builder.makeIntType(32);
2928 break;
2929 case glslang::EbtUint:
2930 spvType = builder.makeUintType(32);
2931 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002932 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002933 spvType = builder.makeIntType(64);
2934 break;
2935 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002936 spvType = builder.makeUintType(64);
2937 break;
John Kessenich426394d2015-07-23 10:22:48 -06002938 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002939 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002940 spvType = builder.makeUintType(32);
2941 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002942#ifdef NV_EXTENSIONS
2943 case glslang::EbtAccStructNV:
2944 spvType = builder.makeAccelerationStructureNVType();
2945 break;
2946#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002947 case glslang::EbtSampler:
2948 {
2949 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002950 if (sampler.sampler) {
2951 // pure sampler
2952 spvType = builder.makeSamplerType();
2953 } else {
2954 // an image is present, make its type
2955 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2956 sampler.image ? 2 : 1, TranslateImageFormat(type));
2957 if (sampler.combined) {
2958 // already has both image and sampler, make the combined type
2959 spvType = builder.makeSampledImageType(spvType);
2960 }
John Kessenich55e7d112015-11-15 21:33:39 -07002961 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002962 }
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EbtStruct:
2965 case glslang::EbtBlock:
2966 {
2967 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002968 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002969
2970 // Try to share structs for different layouts, but not yet for other
2971 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002972 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002973 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002974 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002975 break;
2976
2977 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002978 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002979 memberRemapper[glslangMembers].resize(glslangMembers->size());
2980 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002981 }
2982 break;
2983 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002984 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 }
2987
2988 if (type.isMatrix())
2989 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2990 else {
2991 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2992 if (type.getVectorSize() > 1)
2993 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2994 }
2995
2996 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002997 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2998
John Kessenichc9a80832015-09-12 12:17:44 -06002999 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003000 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003001 // We need to decorate array strides for types needing explicit layout, except blocks.
3002 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003003 // Use a dummy glslang type for querying internal strides of
3004 // arrays of arrays, but using just a one-dimensional array.
3005 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003006 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3007 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003008
3009 // Will compute the higher-order strides here, rather than making a whole
3010 // pile of types and doing repetitive recursion on their contents.
3011 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3012 }
John Kessenichf8842e52016-01-04 19:22:56 -07003013
3014 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003015 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003016 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003017 if (stride > 0)
3018 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003019 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003020 }
3021 } else {
3022 // single-dimensional array, and don't yet have stride
3023
John Kessenichf8842e52016-01-04 19:22:56 -07003024 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003025 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3026 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003027 }
John Kessenich31ed4832015-09-09 17:51:38 -06003028
John Kessenichead86222018-03-28 18:01:20 -06003029 // Do the outer dimension, which might not be known for a runtime-sized array.
3030 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3031 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003032 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003033 else {
3034 if (!lastBufferBlockMember) {
3035 builder.addExtension("SPV_EXT_descriptor_indexing");
3036 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3037 }
John Kessenichead86222018-03-28 18:01:20 -06003038 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003039 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003040 if (stride > 0)
3041 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003042 }
3043
3044 return spvType;
3045}
3046
John Kessenich0e737842017-03-24 18:38:16 -06003047// TODO: this functionality should exist at a higher level, in creating the AST
3048//
3049// Identify interface members that don't have their required extension turned on.
3050//
3051bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3052{
Chao Chen3c366992018-09-19 11:41:59 -07003053#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003054 auto& extensions = glslangIntermediate->getRequestedExtensions();
3055
Rex Xubcf291a2017-03-29 23:01:36 +08003056 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3057 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3058 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003059 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3060 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3061 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003062
3063 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3064 if (member.getFieldName() == "gl_ViewportMask" &&
3065 extensions.find("GL_NV_viewport_array2") == extensions.end())
3066 return true;
3067 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3068 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3069 return true;
3070 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3071 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3072 return true;
3073 }
3074#endif
John Kessenich0e737842017-03-24 18:38:16 -06003075
3076 return false;
3077};
3078
John Kessenich6090df02016-06-30 21:18:02 -06003079// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3080// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3081// Mutually recursive with convertGlslangToSpvType().
3082spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3083 const glslang::TTypeList* glslangMembers,
3084 glslang::TLayoutPacking explicitLayout,
3085 const glslang::TQualifier& qualifier)
3086{
3087 // Create a vector of struct types for SPIR-V to consume
3088 std::vector<spv::Id> spvMembers;
3089 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 -06003090 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3091 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3092 if (glslangMember.hiddenMember()) {
3093 ++memberDelta;
3094 if (type.getBasicType() == glslang::EbtBlock)
3095 memberRemapper[glslangMembers][i] = -1;
3096 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003097 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003098 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003099 if (filterMember(glslangMember))
3100 continue;
3101 }
John Kessenich6090df02016-06-30 21:18:02 -06003102 // modify just this child's view of the qualifier
3103 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3104 InheritQualifiers(memberQualifier, qualifier);
3105
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003106 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003107 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003108 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003109
3110 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003111 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3112 i == (int)glslangMembers->size() - 1;
3113 spvMembers.push_back(
3114 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003115 }
3116 }
3117
3118 // Make the SPIR-V type
3119 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003120 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003121 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3122
3123 // Decorate it
3124 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3125
3126 return spvType;
3127}
3128
3129void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3130 const glslang::TTypeList* glslangMembers,
3131 glslang::TLayoutPacking explicitLayout,
3132 const glslang::TQualifier& qualifier,
3133 spv::Id spvType)
3134{
3135 // Name and decorate the non-hidden members
3136 int offset = -1;
3137 int locationOffset = 0; // for use within the members of this struct
3138 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3139 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3140 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003141 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003142 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003143 if (filterMember(glslangMember))
3144 continue;
3145 }
John Kessenich6090df02016-06-30 21:18:02 -06003146
3147 // modify just this child's view of the qualifier
3148 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3149 InheritQualifiers(memberQualifier, qualifier);
3150
3151 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003152 if (member < 0)
3153 continue;
3154
3155 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3156 builder.addMemberDecoration(spvType, member,
3157 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3158 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3159 // Add interpolation and auxiliary storage decorations only to
3160 // top-level members of Input and Output storage classes
3161 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3162 type.getQualifier().storage == glslang::EvqVaryingOut) {
3163 if (type.getBasicType() == glslang::EbtBlock ||
3164 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3165 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3166 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003167#ifdef NV_EXTENSIONS
3168 addMeshNVDecoration(spvType, member, memberQualifier);
3169#endif
John Kessenich6090df02016-06-30 21:18:02 -06003170 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003171 }
3172 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003173
John Kessenich5d610ee2018-03-07 18:05:55 -07003174 if (type.getBasicType() == glslang::EbtBlock &&
3175 qualifier.storage == glslang::EvqBuffer) {
3176 // Add memory decorations only to top-level members of shader storage block
3177 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003178 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003179 for (unsigned int i = 0; i < memory.size(); ++i)
3180 builder.addMemberDecoration(spvType, member, memory[i]);
3181 }
John Kessenich6090df02016-06-30 21:18:02 -06003182
John Kessenich5d610ee2018-03-07 18:05:55 -07003183 // Location assignment was already completed correctly by the front end,
3184 // just track whether a member needs to be decorated.
3185 // Ignore member locations if the container is an array, as that's
3186 // ill-specified and decisions have been made to not allow this.
3187 if (! type.isArray() && memberQualifier.hasLocation())
3188 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003189
John Kessenich5d610ee2018-03-07 18:05:55 -07003190 if (qualifier.hasLocation()) // track for upcoming inheritance
3191 locationOffset += glslangIntermediate->computeTypeLocationSize(
3192 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003193
John Kessenich5d610ee2018-03-07 18:05:55 -07003194 // component, XFB, others
3195 if (glslangMember.getQualifier().hasComponent())
3196 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3197 glslangMember.getQualifier().layoutComponent);
3198 if (glslangMember.getQualifier().hasXfbOffset())
3199 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3200 glslangMember.getQualifier().layoutXfbOffset);
3201 else if (explicitLayout != glslang::ElpNone) {
3202 // figure out what to do with offset, which is accumulating
3203 int nextOffset;
3204 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3205 if (offset >= 0)
3206 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3207 offset = nextOffset;
3208 }
John Kessenich6090df02016-06-30 21:18:02 -06003209
John Kessenich5d610ee2018-03-07 18:05:55 -07003210 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3211 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3212 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003213
John Kessenich5d610ee2018-03-07 18:05:55 -07003214 // built-in variable decorations
3215 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3216 if (builtIn != spv::BuiltInMax)
3217 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003218
John Kessenich5611c6d2018-04-05 11:25:02 -06003219 // nonuniform
3220 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3221
John Kessenichead86222018-03-28 18:01:20 -06003222 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3223 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3224 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3225 memberQualifier.semanticName);
3226 }
3227
chaoc771d89f2017-01-13 01:10:53 -08003228#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003229 if (builtIn == spv::BuiltInLayer) {
3230 // SPV_NV_viewport_array2 extension
3231 if (glslangMember.getQualifier().layoutViewportRelative){
3232 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3233 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3234 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003235 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003236 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3237 builder.addMemberDecoration(spvType, member,
3238 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3239 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3240 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3241 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003242 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003243 }
3244 if (glslangMember.getQualifier().layoutPassthrough) {
3245 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3246 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3247 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3248 }
chaoc771d89f2017-01-13 01:10:53 -08003249#endif
John Kessenich6090df02016-06-30 21:18:02 -06003250 }
3251
3252 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003253 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3254 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003255 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3256 builder.addCapability(spv::CapabilityGeometryStreams);
3257 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3258 }
John Kessenich6090df02016-06-30 21:18:02 -06003259}
3260
John Kessenich6c292d32016-02-15 20:58:50 -07003261// Turn the expression forming the array size into an id.
3262// This is not quite trivial, because of specialization constants.
3263// Sometimes, a raw constant is turned into an Id, and sometimes
3264// a specialization constant expression is.
3265spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3266{
3267 // First, see if this is sized with a node, meaning a specialization constant:
3268 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3269 if (specNode != nullptr) {
3270 builder.clearAccessChain();
3271 specNode->traverse(this);
3272 return accessChainLoad(specNode->getAsTyped()->getType());
3273 }
qining25262b32016-05-06 17:25:16 -04003274
John Kessenich6c292d32016-02-15 20:58:50 -07003275 // Otherwise, need a compile-time (front end) size, get it:
3276 int size = arraySizes.getDimSize(dim);
3277 assert(size > 0);
3278 return builder.makeUintConstant(size);
3279}
3280
John Kessenich103bef92016-02-08 21:38:15 -07003281// Wrap the builder's accessChainLoad to:
3282// - localize handling of RelaxedPrecision
3283// - use the SPIR-V inferred type instead of another conversion of the glslang type
3284// (avoids unnecessary work and possible type punning for structures)
3285// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003286spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3287{
John Kessenich103bef92016-02-08 21:38:15 -07003288 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003289
3290 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3291 coherentFlags |= TranslateCoherent(type);
3292
John Kessenich5611c6d2018-04-05 11:25:02 -06003293 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003294 TranslateNonUniformDecoration(type.getQualifier()),
3295 nominalTypeId,
3296 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3297 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003298
3299 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003300 if (type.getBasicType() == glslang::EbtBool) {
3301 if (builder.isScalarType(nominalTypeId)) {
3302 // Conversion for bool
3303 spv::Id boolType = builder.makeBoolType();
3304 if (nominalTypeId != boolType)
3305 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3306 } else if (builder.isVectorType(nominalTypeId)) {
3307 // Conversion for bvec
3308 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3309 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3310 if (nominalTypeId != bvecType)
3311 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3312 }
3313 }
John Kessenich103bef92016-02-08 21:38:15 -07003314
3315 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003316}
3317
Rex Xu27253232016-02-23 17:51:09 +08003318// Wrap the builder's accessChainStore to:
3319// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003320//
3321// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003322void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3323{
3324 // Need to convert to abstract types when necessary
3325 if (type.getBasicType() == glslang::EbtBool) {
3326 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3327
3328 if (builder.isScalarType(nominalTypeId)) {
3329 // Conversion for bool
3330 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003331 if (nominalTypeId != boolType) {
3332 // keep these outside arguments, for determinant order-of-evaluation
3333 spv::Id one = builder.makeUintConstant(1);
3334 spv::Id zero = builder.makeUintConstant(0);
3335 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3336 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003337 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003338 } else if (builder.isVectorType(nominalTypeId)) {
3339 // Conversion for bvec
3340 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3341 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003342 if (nominalTypeId != bvecType) {
3343 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003344 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3345 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3346 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003347 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003348 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3349 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003350 }
3351 }
3352
Jeff Bolz36831c92018-09-05 10:11:41 -05003353 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3354 coherentFlags |= TranslateCoherent(type);
3355
3356 builder.accessChainStore(rvalue,
3357 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3358 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003359}
3360
John Kessenich4bf71552016-09-02 11:20:21 -06003361// For storing when types match at the glslang level, but not might match at the
3362// SPIR-V level.
3363//
3364// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003365// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003366// as in a member-decorated way.
3367//
3368// NOTE: This function can handle any store request; if it's not special it
3369// simplifies to a simple OpStore.
3370//
3371// Implicitly uses the existing builder.accessChain as the storage target.
3372void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3373{
John Kessenichb3e24e42016-09-11 12:33:43 -06003374 // we only do the complex path here if it's an aggregate
3375 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003376 accessChainStore(type, rValue);
3377 return;
3378 }
3379
John Kessenichb3e24e42016-09-11 12:33:43 -06003380 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003381 spv::Id rType = builder.getTypeId(rValue);
3382 spv::Id lValue = builder.accessChainGetLValue();
3383 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3384 if (lType == rType) {
3385 accessChainStore(type, rValue);
3386 return;
3387 }
3388
John Kessenichb3e24e42016-09-11 12:33:43 -06003389 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003390 // where the two types were the same type in GLSL. This requires member
3391 // by member copy, recursively.
3392
John Kessenichb3e24e42016-09-11 12:33:43 -06003393 // If an array, copy element by element.
3394 if (type.isArray()) {
3395 glslang::TType glslangElementType(type, 0);
3396 spv::Id elementRType = builder.getContainedTypeId(rType);
3397 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3398 // get the source member
3399 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003400
John Kessenichb3e24e42016-09-11 12:33:43 -06003401 // set up the target storage
3402 builder.clearAccessChain();
3403 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003404 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003405
John Kessenichb3e24e42016-09-11 12:33:43 -06003406 // store the member
3407 multiTypeStore(glslangElementType, elementRValue);
3408 }
3409 } else {
3410 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003411
John Kessenichb3e24e42016-09-11 12:33:43 -06003412 // loop over structure members
3413 const glslang::TTypeList& members = *type.getStruct();
3414 for (int m = 0; m < (int)members.size(); ++m) {
3415 const glslang::TType& glslangMemberType = *members[m].type;
3416
3417 // get the source member
3418 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3419 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3420
3421 // set up the target storage
3422 builder.clearAccessChain();
3423 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003424 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003425
3426 // store the member
3427 multiTypeStore(glslangMemberType, memberRValue);
3428 }
John Kessenich4bf71552016-09-02 11:20:21 -06003429 }
3430}
3431
John Kessenichf85e8062015-12-19 13:57:10 -07003432// Decide whether or not this type should be
3433// decorated with offsets and strides, and if so
3434// whether std140 or std430 rules should be applied.
3435glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003436{
John Kessenichf85e8062015-12-19 13:57:10 -07003437 // has to be a block
3438 if (type.getBasicType() != glslang::EbtBlock)
3439 return glslang::ElpNone;
3440
Chao Chen3c366992018-09-19 11:41:59 -07003441 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003442 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003443 type.getQualifier().storage != glslang::EvqBuffer &&
3444 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003445 return glslang::ElpNone;
3446
3447 // return the layout to use
3448 switch (type.getQualifier().layoutPacking) {
3449 case glslang::ElpStd140:
3450 case glslang::ElpStd430:
3451 return type.getQualifier().layoutPacking;
3452 default:
3453 return glslang::ElpNone;
3454 }
John Kessenich31ed4832015-09-09 17:51:38 -06003455}
3456
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003457// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003458int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003459{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003460 int size;
John Kessenich49987892015-12-29 17:11:44 -07003461 int stride;
3462 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003463
3464 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003465}
3466
John Kessenich49987892015-12-29 17:11:44 -07003467// 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 -07003468// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003469int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003470{
John Kessenich49987892015-12-29 17:11:44 -07003471 glslang::TType elementType;
3472 elementType.shallowCopy(matrixType);
3473 elementType.clearArraySizes();
3474
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003475 int size;
John Kessenich49987892015-12-29 17:11:44 -07003476 int stride;
3477 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3478
3479 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003480}
3481
John Kessenich5e4b1242015-08-06 22:53:06 -06003482// Given a member type of a struct, realign the current offset for it, and compute
3483// the next (not yet aligned) offset for the next member, which will get aligned
3484// on the next call.
3485// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3486// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3487// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003488void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003489 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003490{
3491 // this will get a positive value when deemed necessary
3492 nextOffset = -1;
3493
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 // override anything in currentOffset with user-set offset
3495 if (memberType.getQualifier().hasOffset())
3496 currentOffset = memberType.getQualifier().layoutOffset;
3497
3498 // It could be that current linker usage in glslang updated all the layoutOffset,
3499 // in which case the following code does not matter. But, that's not quite right
3500 // once cross-compilation unit GLSL validation is done, as the original user
3501 // settings are needed in layoutOffset, and then the following will come into play.
3502
John Kessenichf85e8062015-12-19 13:57:10 -07003503 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003504 if (! memberType.getQualifier().hasOffset())
3505 currentOffset = -1;
3506
3507 return;
3508 }
3509
John Kessenichf85e8062015-12-19 13:57:10 -07003510 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 if (currentOffset < 0)
3512 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003513
John Kessenich5e4b1242015-08-06 22:53:06 -06003514 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3515 // but possibly not yet correctly aligned.
3516
3517 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003518 int dummyStride;
3519 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003520
3521 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003522 // TODO: make this consistent in early phases of code:
3523 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3524 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3525 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003526 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003527 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003528 int dummySize;
3529 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3530 if (componentAlignment <= 4)
3531 memberAlignment = componentAlignment;
3532 }
3533
3534 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003536
3537 // Bump up to vec4 if there is a bad straddle
3538 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3539 glslang::RoundToPow2(currentOffset, 16);
3540
John Kessenich5e4b1242015-08-06 22:53:06 -06003541 nextOffset = currentOffset + memberSize;
3542}
3543
David Netoa901ffe2016-06-08 14:11:40 +01003544void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003545{
David Netoa901ffe2016-06-08 14:11:40 +01003546 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3547 switch (glslangBuiltIn)
3548 {
3549 case glslang::EbvClipDistance:
3550 case glslang::EbvCullDistance:
3551 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003552#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003553 case glslang::EbvViewportMaskNV:
3554 case glslang::EbvSecondaryPositionNV:
3555 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003556 case glslang::EbvPositionPerViewNV:
3557 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003558 case glslang::EbvTaskCountNV:
3559 case glslang::EbvPrimitiveCountNV:
3560 case glslang::EbvPrimitiveIndicesNV:
3561 case glslang::EbvClipDistancePerViewNV:
3562 case glslang::EbvCullDistancePerViewNV:
3563 case glslang::EbvLayerPerViewNV:
3564 case glslang::EbvMeshViewCountNV:
3565 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003566#endif
David Netoa901ffe2016-06-08 14:11:40 +01003567 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3568 // Alternately, we could just call this for any glslang built-in, since the
3569 // capability already guards against duplicates.
3570 TranslateBuiltInDecoration(glslangBuiltIn, false);
3571 break;
3572 default:
3573 // Capabilities were already generated when the struct was declared.
3574 break;
3575 }
John Kessenichebb50532016-05-16 19:22:05 -06003576}
3577
John Kessenich6fccb3c2016-09-19 16:01:41 -06003578bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003579{
John Kessenicheee9d532016-09-19 18:09:30 -06003580 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003581}
3582
John Kessenichd41993d2017-09-10 15:21:05 -06003583// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003584// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3585// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003586bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003587{
John Kessenich6a14f782017-12-04 02:48:10 -07003588 assert(qualifier == glslang::EvqIn ||
3589 qualifier == glslang::EvqOut ||
3590 qualifier == glslang::EvqInOut ||
3591 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003592 return qualifier != glslang::EvqConstReadOnly;
3593}
3594
3595// Is parameter pass-by-original?
3596bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3597 bool implicitThisParam)
3598{
3599 if (implicitThisParam) // implicit this
3600 return true;
3601 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003602 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003603 return paramType.containsOpaque() || // sampler, etc.
3604 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3605}
3606
John Kessenich140f3df2015-06-26 16:58:36 -06003607// Make all the functions, skeletally, without actually visiting their bodies.
3608void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3609{
Jeff Bolz36831c92018-09-05 10:11:41 -05003610 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003611 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3612 if (paramPrecision != spv::NoPrecision)
3613 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003614 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003615 };
3616
John Kessenich140f3df2015-06-26 16:58:36 -06003617 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3618 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003619 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003620 continue;
3621
3622 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003623 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003624 //
qining25262b32016-05-06 17:25:16 -04003625 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003626 // function. What it is an address of varies:
3627 //
John Kessenich4bf71552016-09-02 11:20:21 -06003628 // - "in" parameters not marked as "const" can be written to without modifying the calling
3629 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003630 //
3631 // - "const in" parameters can just be the r-value, as no writes need occur.
3632 //
John Kessenich4bf71552016-09-02 11:20:21 -06003633 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3634 // 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 -06003635
3636 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003637 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003638 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3639
John Kessenichfad62972017-07-18 02:35:46 -06003640 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3641 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003642
John Kessenichfad62972017-07-18 02:35:46 -06003643 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003644 for (int p = 0; p < (int)parameters.size(); ++p) {
3645 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3646 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003647 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003648 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003649 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003650 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3651 else
John Kessenich4bf71552016-09-02 11:20:21 -06003652 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003653 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003654 paramTypes.push_back(typeId);
3655 }
3656
3657 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003658 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3659 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003660 glslFunction->getName().c_str(), paramTypes,
3661 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003662 if (implicitThis)
3663 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003664
3665 // Track function to emit/call later
3666 functionMap[glslFunction->getName().c_str()] = function;
3667
3668 // Set the parameter id's
3669 for (int p = 0; p < (int)parameters.size(); ++p) {
3670 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3671 // give a name too
3672 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3673 }
3674 }
3675}
3676
3677// Process all the initializers, while skipping the functions and link objects
3678void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3679{
3680 builder.setBuildPoint(shaderEntry->getLastBlock());
3681 for (int i = 0; i < (int)initializers.size(); ++i) {
3682 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3683 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3684
3685 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003686 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003687 initializer->traverse(this);
3688 }
3689 }
3690}
3691
3692// Process all the functions, while skipping initializers.
3693void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3694{
3695 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3696 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003697 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003698 node->traverse(this);
3699 }
3700}
3701
3702void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3703{
qining25262b32016-05-06 17:25:16 -04003704 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003705 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003706 currentFunction = functionMap[node->getName().c_str()];
3707 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003708 builder.setBuildPoint(functionBlock);
3709}
3710
Rex Xu04db3f52015-09-16 11:44:02 +08003711void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003712{
Rex Xufc618912015-09-09 16:42:49 +08003713 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003714
3715 glslang::TSampler sampler = {};
3716 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003717#ifdef AMD_EXTENSIONS
3718 bool f16ShadowCompare = false;
3719#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003720 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003721 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3722 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003723#ifdef AMD_EXTENSIONS
3724 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3725#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003726 }
3727
John Kessenich140f3df2015-06-26 16:58:36 -06003728 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3729 builder.clearAccessChain();
3730 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003731
3732 // Special case l-value operands
3733 bool lvalue = false;
3734 switch (node.getOp()) {
3735 case glslang::EOpImageAtomicAdd:
3736 case glslang::EOpImageAtomicMin:
3737 case glslang::EOpImageAtomicMax:
3738 case glslang::EOpImageAtomicAnd:
3739 case glslang::EOpImageAtomicOr:
3740 case glslang::EOpImageAtomicXor:
3741 case glslang::EOpImageAtomicExchange:
3742 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003743 case glslang::EOpImageAtomicLoad:
3744 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003745 if (i == 0)
3746 lvalue = true;
3747 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003748 case glslang::EOpSparseImageLoad:
3749 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3750 lvalue = true;
3751 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003752#ifdef AMD_EXTENSIONS
3753 case glslang::EOpSparseTexture:
3754 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3755 lvalue = true;
3756 break;
3757 case glslang::EOpSparseTextureClamp:
3758 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3759 lvalue = true;
3760 break;
3761 case glslang::EOpSparseTextureLod:
3762 case glslang::EOpSparseTextureOffset:
3763 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3764 lvalue = true;
3765 break;
3766#else
Rex Xu48edadf2015-12-31 16:11:41 +08003767 case glslang::EOpSparseTexture:
3768 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3769 lvalue = true;
3770 break;
3771 case glslang::EOpSparseTextureClamp:
3772 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3773 lvalue = true;
3774 break;
3775 case glslang::EOpSparseTextureLod:
3776 case glslang::EOpSparseTextureOffset:
3777 if (i == 3)
3778 lvalue = true;
3779 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003780#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003781 case glslang::EOpSparseTextureFetch:
3782 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3783 lvalue = true;
3784 break;
3785 case glslang::EOpSparseTextureFetchOffset:
3786 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3787 lvalue = true;
3788 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003789#ifdef AMD_EXTENSIONS
3790 case glslang::EOpSparseTextureLodOffset:
3791 case glslang::EOpSparseTextureGrad:
3792 case glslang::EOpSparseTextureOffsetClamp:
3793 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3794 lvalue = true;
3795 break;
3796 case glslang::EOpSparseTextureGradOffset:
3797 case glslang::EOpSparseTextureGradClamp:
3798 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3799 lvalue = true;
3800 break;
3801 case glslang::EOpSparseTextureGradOffsetClamp:
3802 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3803 lvalue = true;
3804 break;
3805#else
Rex Xu48edadf2015-12-31 16:11:41 +08003806 case glslang::EOpSparseTextureLodOffset:
3807 case glslang::EOpSparseTextureGrad:
3808 case glslang::EOpSparseTextureOffsetClamp:
3809 if (i == 4)
3810 lvalue = true;
3811 break;
3812 case glslang::EOpSparseTextureGradOffset:
3813 case glslang::EOpSparseTextureGradClamp:
3814 if (i == 5)
3815 lvalue = true;
3816 break;
3817 case glslang::EOpSparseTextureGradOffsetClamp:
3818 if (i == 6)
3819 lvalue = true;
3820 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003821#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003822 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003823 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3824 lvalue = true;
3825 break;
3826 case glslang::EOpSparseTextureGatherOffset:
3827 case glslang::EOpSparseTextureGatherOffsets:
3828 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3829 lvalue = true;
3830 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003831#ifdef AMD_EXTENSIONS
3832 case glslang::EOpSparseTextureGatherLod:
3833 if (i == 3)
3834 lvalue = true;
3835 break;
3836 case glslang::EOpSparseTextureGatherLodOffset:
3837 case glslang::EOpSparseTextureGatherLodOffsets:
3838 if (i == 4)
3839 lvalue = true;
3840 break;
Rex Xu129799a2017-07-05 17:23:28 +08003841 case glslang::EOpSparseImageLoadLod:
3842 if (i == 3)
3843 lvalue = true;
3844 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003845#endif
Chao Chen3a137962018-09-19 11:41:27 -07003846#ifdef NV_EXTENSIONS
3847 case glslang::EOpImageSampleFootprintNV:
3848 if (i == 4)
3849 lvalue = true;
3850 break;
3851 case glslang::EOpImageSampleFootprintClampNV:
3852 case glslang::EOpImageSampleFootprintLodNV:
3853 if (i == 5)
3854 lvalue = true;
3855 break;
3856 case glslang::EOpImageSampleFootprintGradNV:
3857 if (i == 6)
3858 lvalue = true;
3859 break;
3860 case glslang::EOpImageSampleFootprintGradClampNV:
3861 if (i == 7)
3862 lvalue = true;
3863 break;
3864#endif
Rex Xufc618912015-09-09 16:42:49 +08003865 default:
3866 break;
3867 }
3868
Rex Xu6b86d492015-09-16 17:48:22 +08003869 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003870 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003871 else
John Kessenich32cfd492016-02-02 12:37:46 -07003872 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003873 }
3874}
3875
John Kessenichfc51d282015-08-19 13:34:18 -06003876void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003877{
John Kessenichfc51d282015-08-19 13:34:18 -06003878 builder.clearAccessChain();
3879 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003880 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003881}
John Kessenich140f3df2015-06-26 16:58:36 -06003882
John Kessenichfc51d282015-08-19 13:34:18 -06003883spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3884{
John Kesseniche485c7a2017-05-31 18:50:53 -06003885 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003886 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003887
3888 builder.setLine(node->getLoc().line);
3889
John Kessenichfc51d282015-08-19 13:34:18 -06003890 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003891
3892 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3893 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3894 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003895#ifdef AMD_EXTENSIONS
3896 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3897 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3898 : false;
3899#endif
3900
John Kessenichfc51d282015-08-19 13:34:18 -06003901 std::vector<spv::Id> arguments;
3902 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003903 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003904 else
3905 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003906 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003907
3908 spv::Builder::TextureParameters params = { };
3909 params.sampler = arguments[0];
3910
Rex Xu04db3f52015-09-16 11:44:02 +08003911 glslang::TCrackedTextureOp cracked;
3912 node->crackTexture(sampler, cracked);
3913
amhagan05506bb2017-06-13 16:53:02 -04003914 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003915
John Kessenichfc51d282015-08-19 13:34:18 -06003916 // Check for queries
3917 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003918 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3919 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003920 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003921
John Kessenichfc51d282015-08-19 13:34:18 -06003922 switch (node->getOp()) {
3923 case glslang::EOpImageQuerySize:
3924 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003925 if (arguments.size() > 1) {
3926 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003927 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003928 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003929 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003930 case glslang::EOpImageQuerySamples:
3931 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003932 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003933 case glslang::EOpTextureQueryLod:
3934 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003935 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003936 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003937 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003938 case glslang::EOpSparseTexelsResident:
3939 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003940 default:
3941 assert(0);
3942 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003943 }
John Kessenich140f3df2015-06-26 16:58:36 -06003944 }
3945
LoopDawg4425f242018-02-18 11:40:01 -07003946 int components = node->getType().getVectorSize();
3947
3948 if (node->getOp() == glslang::EOpTextureFetch) {
3949 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3950 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3951 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3952 // here around e.g. which ones return scalars or other types.
3953 components = 4;
3954 }
3955
3956 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3957
3958 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3959
Rex Xufc618912015-09-09 16:42:49 +08003960 // Check for image functions other than queries
3961 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003962 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003963 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003964 spv::IdImmediate image = { true, *(opIt++) };
3965 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003966
3967 // Handle subpass operations
3968 // TODO: GLSL should change to have the "MS" only on the type rather than the
3969 // built-in function.
3970 if (cracked.subpass) {
3971 // add on the (0,0) coordinate
3972 spv::Id zero = builder.makeIntConstant(0);
3973 std::vector<spv::Id> comps;
3974 comps.push_back(zero);
3975 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003976 spv::IdImmediate coord = { true,
3977 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3978 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003979 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003980 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3981 operands.push_back(imageOperands);
3982 spv::IdImmediate imageOperand = { true, *(opIt++) };
3983 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003984 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003985 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3986 builder.setPrecision(result, precision);
3987 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003988 }
3989
John Kessenich149afc32018-08-14 13:31:43 -06003990 spv::IdImmediate coord = { true, *(opIt++) };
3991 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003992#ifdef AMD_EXTENSIONS
3993 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3994#else
John Kessenich56bab042015-09-16 10:54:31 -06003995 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003996#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003997 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003998 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003999 mask = mask | spv::ImageOperandsSampleMask;
4000 }
Rex Xu129799a2017-07-05 17:23:28 +08004001#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004002 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004003 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4004 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004005 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004006 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004007#endif
4008 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4009 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4010 if (mask) {
4011 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4012 operands.push_back(imageOperands);
4013 }
4014 if (mask & spv::ImageOperandsSampleMask) {
4015 spv::IdImmediate imageOperand = { true, *opIt++ };
4016 operands.push_back(imageOperand);
4017 }
4018#ifdef AMD_EXTENSIONS
4019 if (mask & spv::ImageOperandsLodMask) {
4020 spv::IdImmediate imageOperand = { true, *opIt++ };
4021 operands.push_back(imageOperand);
4022 }
4023#endif
4024 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4025 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4026 operands.push_back(imageOperand);
4027 }
4028
John Kessenich149afc32018-08-14 13:31:43 -06004029 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004030 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004031
John Kessenich149afc32018-08-14 13:31:43 -06004032 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004033 builder.setPrecision(result[0], precision);
4034
4035 // If needed, add a conversion constructor to the proper size.
4036 if (components != node->getType().getVectorSize())
4037 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4038
4039 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004040#ifdef AMD_EXTENSIONS
4041 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4042#else
John Kessenich56bab042015-09-16 10:54:31 -06004043 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004044#endif
Rex Xu129799a2017-07-05 17:23:28 +08004045
Jeff Bolz36831c92018-09-05 10:11:41 -05004046 // Push the texel value before the operands
4047#ifdef AMD_EXTENSIONS
4048 if (sampler.ms || cracked.lod) {
4049#else
4050 if (sampler.ms) {
4051#endif
John Kessenich149afc32018-08-14 13:31:43 -06004052 spv::IdImmediate texel = { true, *(opIt + 1) };
4053 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004054 } else {
4055 spv::IdImmediate texel = { true, *opIt };
4056 operands.push_back(texel);
4057 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004058
4059 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4060 if (sampler.ms) {
4061 mask = mask | spv::ImageOperandsSampleMask;
4062 }
4063#ifdef AMD_EXTENSIONS
4064 if (cracked.lod) {
4065 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4066 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4067 mask = mask | spv::ImageOperandsLodMask;
4068 }
4069#endif
4070 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4071 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4072 if (mask) {
4073 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4074 operands.push_back(imageOperands);
4075 }
4076 if (mask & spv::ImageOperandsSampleMask) {
4077 spv::IdImmediate imageOperand = { true, *opIt++ };
4078 operands.push_back(imageOperand);
4079 }
4080#ifdef AMD_EXTENSIONS
4081 if (mask & spv::ImageOperandsLodMask) {
4082 spv::IdImmediate imageOperand = { true, *opIt++ };
4083 operands.push_back(imageOperand);
4084 }
4085#endif
4086 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4087 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4088 operands.push_back(imageOperand);
4089 }
4090
John Kessenich56bab042015-09-16 10:54:31 -06004091 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004092 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004093 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004094 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004095#ifdef AMD_EXTENSIONS
4096 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4097#else
Rex Xu5eafa472016-02-19 22:24:03 +08004098 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004099#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004100 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004101 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004102 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4103
Jeff Bolz36831c92018-09-05 10:11:41 -05004104 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004105 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004106 mask = mask | spv::ImageOperandsSampleMask;
4107 }
Rex Xu129799a2017-07-05 17:23:28 +08004108#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004109 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004110 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4111 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4112
Jeff Bolz36831c92018-09-05 10:11:41 -05004113 mask = mask | spv::ImageOperandsLodMask;
4114 }
4115#endif
4116 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4117 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4118 if (mask) {
4119 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004120 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004121 }
4122 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004123 spv::IdImmediate imageOperand = { true, *opIt++ };
4124 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004125 }
4126#ifdef AMD_EXTENSIONS
4127 if (mask & spv::ImageOperandsLodMask) {
4128 spv::IdImmediate imageOperand = { true, *opIt++ };
4129 operands.push_back(imageOperand);
4130 }
Rex Xu129799a2017-07-05 17:23:28 +08004131#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004132 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4133 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4134 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004135 }
4136
4137 // Create the return type that was a special structure
4138 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004139 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004140 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4141 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4142
4143 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4144
4145 // Decode the return type
4146 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4147 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004148 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004149 // Process image atomic operations
4150
4151 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4152 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004153 // For non-MS, the sample value should be 0
4154 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4155 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004156
Jeff Bolz36831c92018-09-05 10:11:41 -05004157 spv::Id resultTypeId;
4158 // imageAtomicStore has a void return type so base the pointer type on
4159 // the type of the value operand.
4160 if (node->getOp() == glslang::EOpImageAtomicStore) {
4161 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4162 } else {
4163 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4164 }
John Kessenich56bab042015-09-16 10:54:31 -06004165 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004166
4167 std::vector<spv::Id> operands;
4168 operands.push_back(pointer);
4169 for (; opIt != arguments.end(); ++opIt)
4170 operands.push_back(*opIt);
4171
John Kessenich8c8505c2016-07-26 12:50:38 -06004172 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004173 }
4174 }
4175
amhagan05506bb2017-06-13 16:53:02 -04004176#ifdef AMD_EXTENSIONS
4177 // Check for fragment mask functions other than queries
4178 if (cracked.fragMask) {
4179 assert(sampler.ms);
4180
4181 auto opIt = arguments.begin();
4182 std::vector<spv::Id> operands;
4183
4184 // Extract the image if necessary
4185 if (builder.isSampledImage(params.sampler))
4186 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4187
4188 operands.push_back(params.sampler);
4189 ++opIt;
4190
4191 if (sampler.isSubpass()) {
4192 // add on the (0,0) coordinate
4193 spv::Id zero = builder.makeIntConstant(0);
4194 std::vector<spv::Id> comps;
4195 comps.push_back(zero);
4196 comps.push_back(zero);
4197 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4198 }
4199
4200 for (; opIt != arguments.end(); ++opIt)
4201 operands.push_back(*opIt);
4202
4203 spv::Op fragMaskOp = spv::OpNop;
4204 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4205 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4206 else if (node->getOp() == glslang::EOpFragmentFetch)
4207 fragMaskOp = spv::OpFragmentFetchAMD;
4208
4209 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4210 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4211 return builder.createOp(fragMaskOp, resultType(), operands);
4212 }
4213#endif
4214
Rex Xufc618912015-09-09 16:42:49 +08004215 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004216 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004217#ifdef NV_EXTENSIONS
4218 bool imageFootprint = node->isImageFootprint();
4219#endif
4220
Rex Xu71519fe2015-11-11 15:35:47 +08004221 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4222
John Kessenichfc51d282015-08-19 13:34:18 -06004223 // check for bias argument
4224 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004225#ifdef AMD_EXTENSIONS
4226 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4227#else
Rex Xu71519fe2015-11-11 15:35:47 +08004228 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004229#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004230 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004231#ifdef AMD_EXTENSIONS
4232 if (cracked.gather)
4233 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004234
4235 if (f16ShadowCompare)
4236 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004237#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004238 if (cracked.offset)
4239 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004240#ifdef AMD_EXTENSIONS
4241 else if (cracked.offsets)
4242 ++nonBiasArgCount;
4243#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004244 if (cracked.grad)
4245 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004246 if (cracked.lodClamp)
4247 ++nonBiasArgCount;
4248 if (sparse)
4249 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004250#ifdef NV_EXTENSIONS
4251 if (imageFootprint)
4252 //Following three extra arguments
4253 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4254 nonBiasArgCount += 3;
4255#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004256 if ((int)arguments.size() > nonBiasArgCount)
4257 bias = true;
4258 }
4259
John Kessenicha5c33d62016-06-02 23:45:21 -06004260 // See if the sampler param should really be just the SPV image part
4261 if (cracked.fetch) {
4262 // a fetch needs to have the image extracted first
4263 if (builder.isSampledImage(params.sampler))
4264 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4265 }
4266
Rex Xu225e0fc2016-11-17 17:47:59 +08004267#ifdef AMD_EXTENSIONS
4268 if (cracked.gather) {
4269 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4270 if (bias || cracked.lod ||
4271 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4272 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004273 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004274 }
4275 }
4276#endif
4277
John Kessenichfc51d282015-08-19 13:34:18 -06004278 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004279
John Kessenichfc51d282015-08-19 13:34:18 -06004280 params.coords = arguments[1];
4281 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004282 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004283
4284 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004285#ifdef AMD_EXTENSIONS
4286 if (cubeCompare || f16ShadowCompare) {
4287#else
Rex Xu48edadf2015-12-31 16:11:41 +08004288 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004289#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004290 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004291 ++extraArgs;
4292 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004293 params.Dref = arguments[2];
4294 ++extraArgs;
4295 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004296 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004297 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004298 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004299 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004300 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004301 dRefComp = builder.getNumComponents(params.coords) - 1;
4302 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004303 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4304 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004305
4306 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004307 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004308 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004309 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004310 } else if (glslangIntermediate->getStage() != EShLangFragment
4311#ifdef NV_EXTENSIONS
4312 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4313 && !(glslangIntermediate->getStage() == EShLangCompute &&
4314 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4315#endif
4316 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004317 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4318 noImplicitLod = true;
4319 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004320
4321 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004322 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004323 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004324 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004325 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004326
4327 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004328 if (cracked.grad) {
4329 params.gradX = arguments[2 + extraArgs];
4330 params.gradY = arguments[3 + extraArgs];
4331 extraArgs += 2;
4332 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004333
4334 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004335 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004336 params.offset = arguments[2 + extraArgs];
4337 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004338 } else if (cracked.offsets) {
4339 params.offsets = arguments[2 + extraArgs];
4340 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004341 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004342
4343 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004344 if (cracked.lodClamp) {
4345 params.lodClamp = arguments[2 + extraArgs];
4346 ++extraArgs;
4347 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004348 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004349 if (sparse) {
4350 params.texelOut = arguments[2 + extraArgs];
4351 ++extraArgs;
4352 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004353
John Kessenich76d4dfc2016-06-16 12:43:23 -06004354 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004355 if (cracked.gather && ! sampler.shadow) {
4356 // default component is 0, if missing, otherwise an argument
4357 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004358 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004359 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004360 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004361 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004362 }
Chao Chen3a137962018-09-19 11:41:27 -07004363#ifdef NV_EXTENSIONS
4364 spv::Id resultStruct = spv::NoResult;
4365 if (imageFootprint) {
4366 //Following three extra arguments
4367 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4368 params.granularity = arguments[2 + extraArgs];
4369 params.coarse = arguments[3 + extraArgs];
4370 resultStruct = arguments[4 + extraArgs];
4371 extraArgs += 3;
4372 }
4373#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004374 // bias
4375 if (bias) {
4376 params.bias = arguments[2 + extraArgs];
4377 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004378 }
John Kessenichfc51d282015-08-19 13:34:18 -06004379
Chao Chen3a137962018-09-19 11:41:27 -07004380#ifdef NV_EXTENSIONS
4381 if (imageFootprint) {
4382 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4383 builder.addCapability(spv::CapabilityImageFootprintNV);
4384
4385
4386 //resultStructType(OpenGL type) contains 5 elements:
4387 //struct gl_TextureFootprint2DNV {
4388 // uvec2 anchor;
4389 // uvec2 offset;
4390 // uvec2 mask;
4391 // uint lod;
4392 // uint granularity;
4393 //};
4394 //or
4395 //struct gl_TextureFootprint3DNV {
4396 // uvec3 anchor;
4397 // uvec3 offset;
4398 // uvec2 mask;
4399 // uint lod;
4400 // uint granularity;
4401 //};
4402 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4403 assert(builder.isStructType(resultStructType));
4404
4405 //resType (SPIR-V type) contains 6 elements:
4406 //Member 0 must be a Boolean type scalar(LOD),
4407 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4408 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4409 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4410 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4411 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4412 std::vector<spv::Id> members;
4413 members.push_back(resultType());
4414 for (int i = 0; i < 5; i++) {
4415 members.push_back(builder.getContainedTypeId(resultStructType, i));
4416 }
4417 spv::Id resType = builder.makeStructType(members, "ResType");
4418
4419 //call ImageFootprintNV
4420 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4421
4422 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4423 for (int i = 0; i < 5; i++) {
4424 builder.clearAccessChain();
4425 builder.setAccessChainLValue(resultStruct);
4426
4427 //Accessing to a struct we created, no coherent flag is set
4428 spv::Builder::AccessChain::CoherentFlags flags;
4429 flags.clear();
4430
4431 builder.accessChainPush(builder.makeIntConstant(i), flags);
4432 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4433 }
4434 return builder.createCompositeExtract(res, resultType(), 0);
4435 }
4436#endif
4437
John Kessenich65336482016-06-16 14:06:26 -06004438 // projective component (might not to move)
4439 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4440 // are divided by the last component of P."
4441 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4442 // unused components will appear after all used components."
4443 if (cracked.proj) {
4444 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4445 int projTargetComp;
4446 switch (sampler.dim) {
4447 case glslang::Esd1D: projTargetComp = 1; break;
4448 case glslang::Esd2D: projTargetComp = 2; break;
4449 case glslang::EsdRect: projTargetComp = 2; break;
4450 default: projTargetComp = projSourceComp; break;
4451 }
4452 // copy the projective coordinate if we have to
4453 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004454 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004455 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4456 projSourceComp);
4457 params.coords = builder.createCompositeInsert(projComp, params.coords,
4458 builder.getTypeId(params.coords), projTargetComp);
4459 }
4460 }
4461
Jeff Bolz36831c92018-09-05 10:11:41 -05004462 // nonprivate
4463 if (imageType.getQualifier().nonprivate) {
4464 params.nonprivate = true;
4465 }
4466
4467 // volatile
4468 if (imageType.getQualifier().volatil) {
4469 params.volatil = true;
4470 }
4471
St0fFa1184dd2018-04-09 21:08:14 +02004472 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004473 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004474 );
LoopDawg4425f242018-02-18 11:40:01 -07004475
4476 if (components != node->getType().getVectorSize())
4477 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4478
4479 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004480}
4481
4482spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4483{
4484 // Grab the function's pointer from the previously created function
4485 spv::Function* function = functionMap[node->getName().c_str()];
4486 if (! function)
4487 return 0;
4488
4489 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4490 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4491
4492 // See comments in makeFunctions() for details about the semantics for parameter passing.
4493 //
4494 // These imply we need a four step process:
4495 // 1. Evaluate the arguments
4496 // 2. Allocate and make copies of in, out, and inout arguments
4497 // 3. Make the call
4498 // 4. Copy back the results
4499
John Kessenichd3ed90b2018-05-04 11:43:03 -06004500 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004501 std::vector<spv::Builder::AccessChain> lValues;
4502 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004503 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004504 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004505 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004506 // build l-value
4507 builder.clearAccessChain();
4508 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004509 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004510 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004511 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004512 // save l-value
4513 lValues.push_back(builder.getAccessChain());
4514 } else {
4515 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004516 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004517 }
4518 }
4519
4520 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4521 // copy the original into that space.
4522 //
4523 // Also, build up the list of actual arguments to pass in for the call
4524 int lValueCount = 0;
4525 int rValueCount = 0;
4526 std::vector<spv::Id> spvArgs;
4527 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4528 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004529 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004530 builder.setAccessChain(lValues[lValueCount]);
4531 arg = builder.accessChainGetLValue();
4532 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004533 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004534 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004535 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004536 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4537 // need to copy the input into output space
4538 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004539 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004540 builder.clearAccessChain();
4541 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004542 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004543 }
4544 ++lValueCount;
4545 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004546 // process r-value, which involves a copy for a type mismatch
4547 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4548 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4549 builder.clearAccessChain();
4550 builder.setAccessChainLValue(argCopy);
4551 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4552 arg = builder.createLoad(argCopy);
4553 } else
4554 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004555 ++rValueCount;
4556 }
4557 spvArgs.push_back(arg);
4558 }
4559
4560 // 3. Make the call.
4561 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004562 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004563
4564 // 4. Copy back out an "out" arguments.
4565 lValueCount = 0;
4566 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004567 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004568 ++lValueCount;
4569 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004570 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4571 spv::Id copy = builder.createLoad(spvArgs[a]);
4572 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004573 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004574 }
4575 ++lValueCount;
4576 }
4577 }
4578
4579 return result;
4580}
4581
4582// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004583spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004584 spv::Id typeId, spv::Id left, spv::Id right,
4585 glslang::TBasicType typeProxy, bool reduceComparison)
4586{
John Kessenich66011cb2018-03-06 16:12:04 -07004587 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4588 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004589 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004590
4591 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004592 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004593 bool comparison = false;
4594
4595 switch (op) {
4596 case glslang::EOpAdd:
4597 case glslang::EOpAddAssign:
4598 if (isFloat)
4599 binOp = spv::OpFAdd;
4600 else
4601 binOp = spv::OpIAdd;
4602 break;
4603 case glslang::EOpSub:
4604 case glslang::EOpSubAssign:
4605 if (isFloat)
4606 binOp = spv::OpFSub;
4607 else
4608 binOp = spv::OpISub;
4609 break;
4610 case glslang::EOpMul:
4611 case glslang::EOpMulAssign:
4612 if (isFloat)
4613 binOp = spv::OpFMul;
4614 else
4615 binOp = spv::OpIMul;
4616 break;
4617 case glslang::EOpVectorTimesScalar:
4618 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004619 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004620 if (builder.isVector(right))
4621 std::swap(left, right);
4622 assert(builder.isScalar(right));
4623 needMatchingVectors = false;
4624 binOp = spv::OpVectorTimesScalar;
4625 } else
4626 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004627 break;
4628 case glslang::EOpVectorTimesMatrix:
4629 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004630 binOp = spv::OpVectorTimesMatrix;
4631 break;
4632 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004633 binOp = spv::OpMatrixTimesVector;
4634 break;
4635 case glslang::EOpMatrixTimesScalar:
4636 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004637 binOp = spv::OpMatrixTimesScalar;
4638 break;
4639 case glslang::EOpMatrixTimesMatrix:
4640 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004641 binOp = spv::OpMatrixTimesMatrix;
4642 break;
4643 case glslang::EOpOuterProduct:
4644 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004645 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004646 break;
4647
4648 case glslang::EOpDiv:
4649 case glslang::EOpDivAssign:
4650 if (isFloat)
4651 binOp = spv::OpFDiv;
4652 else if (isUnsigned)
4653 binOp = spv::OpUDiv;
4654 else
4655 binOp = spv::OpSDiv;
4656 break;
4657 case glslang::EOpMod:
4658 case glslang::EOpModAssign:
4659 if (isFloat)
4660 binOp = spv::OpFMod;
4661 else if (isUnsigned)
4662 binOp = spv::OpUMod;
4663 else
4664 binOp = spv::OpSMod;
4665 break;
4666 case glslang::EOpRightShift:
4667 case glslang::EOpRightShiftAssign:
4668 if (isUnsigned)
4669 binOp = spv::OpShiftRightLogical;
4670 else
4671 binOp = spv::OpShiftRightArithmetic;
4672 break;
4673 case glslang::EOpLeftShift:
4674 case glslang::EOpLeftShiftAssign:
4675 binOp = spv::OpShiftLeftLogical;
4676 break;
4677 case glslang::EOpAnd:
4678 case glslang::EOpAndAssign:
4679 binOp = spv::OpBitwiseAnd;
4680 break;
4681 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004682 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004683 binOp = spv::OpLogicalAnd;
4684 break;
4685 case glslang::EOpInclusiveOr:
4686 case glslang::EOpInclusiveOrAssign:
4687 binOp = spv::OpBitwiseOr;
4688 break;
4689 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004690 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004691 binOp = spv::OpLogicalOr;
4692 break;
4693 case glslang::EOpExclusiveOr:
4694 case glslang::EOpExclusiveOrAssign:
4695 binOp = spv::OpBitwiseXor;
4696 break;
4697 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004698 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004699 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004700 break;
4701
4702 case glslang::EOpLessThan:
4703 case glslang::EOpGreaterThan:
4704 case glslang::EOpLessThanEqual:
4705 case glslang::EOpGreaterThanEqual:
4706 case glslang::EOpEqual:
4707 case glslang::EOpNotEqual:
4708 case glslang::EOpVectorEqual:
4709 case glslang::EOpVectorNotEqual:
4710 comparison = true;
4711 break;
4712 default:
4713 break;
4714 }
4715
John Kessenich7c1aa102015-10-15 13:29:11 -06004716 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004717 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004718 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004719 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004720 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004721
4722 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004723 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004724 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004725
qining25262b32016-05-06 17:25:16 -04004726 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004727 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004728 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004729 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004730 }
4731
4732 if (! comparison)
4733 return 0;
4734
John Kessenich7c1aa102015-10-15 13:29:11 -06004735 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004736
John Kessenich4583b612016-08-07 19:14:22 -06004737 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004738 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4739 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004740 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004741 return result;
4742 }
John Kessenich140f3df2015-06-26 16:58:36 -06004743
4744 switch (op) {
4745 case glslang::EOpLessThan:
4746 if (isFloat)
4747 binOp = spv::OpFOrdLessThan;
4748 else if (isUnsigned)
4749 binOp = spv::OpULessThan;
4750 else
4751 binOp = spv::OpSLessThan;
4752 break;
4753 case glslang::EOpGreaterThan:
4754 if (isFloat)
4755 binOp = spv::OpFOrdGreaterThan;
4756 else if (isUnsigned)
4757 binOp = spv::OpUGreaterThan;
4758 else
4759 binOp = spv::OpSGreaterThan;
4760 break;
4761 case glslang::EOpLessThanEqual:
4762 if (isFloat)
4763 binOp = spv::OpFOrdLessThanEqual;
4764 else if (isUnsigned)
4765 binOp = spv::OpULessThanEqual;
4766 else
4767 binOp = spv::OpSLessThanEqual;
4768 break;
4769 case glslang::EOpGreaterThanEqual:
4770 if (isFloat)
4771 binOp = spv::OpFOrdGreaterThanEqual;
4772 else if (isUnsigned)
4773 binOp = spv::OpUGreaterThanEqual;
4774 else
4775 binOp = spv::OpSGreaterThanEqual;
4776 break;
4777 case glslang::EOpEqual:
4778 case glslang::EOpVectorEqual:
4779 if (isFloat)
4780 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004781 else if (isBool)
4782 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004783 else
4784 binOp = spv::OpIEqual;
4785 break;
4786 case glslang::EOpNotEqual:
4787 case glslang::EOpVectorNotEqual:
4788 if (isFloat)
4789 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004790 else if (isBool)
4791 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 else
4793 binOp = spv::OpINotEqual;
4794 break;
4795 default:
4796 break;
4797 }
4798
qining25262b32016-05-06 17:25:16 -04004799 if (binOp != spv::OpNop) {
4800 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004801 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004802 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004803 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004804 }
John Kessenich140f3df2015-06-26 16:58:36 -06004805
4806 return 0;
4807}
4808
John Kessenich04bb8a02015-12-12 12:28:14 -07004809//
4810// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4811// These can be any of:
4812//
4813// matrix * scalar
4814// scalar * matrix
4815// matrix * matrix linear algebraic
4816// matrix * vector
4817// vector * matrix
4818// matrix * matrix componentwise
4819// matrix op matrix op in {+, -, /}
4820// matrix op scalar op in {+, -, /}
4821// scalar op matrix op in {+, -, /}
4822//
John Kessenichead86222018-03-28 18:01:20 -06004823spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4824 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004825{
4826 bool firstClass = true;
4827
4828 // First, handle first-class matrix operations (* and matrix/scalar)
4829 switch (op) {
4830 case spv::OpFDiv:
4831 if (builder.isMatrix(left) && builder.isScalar(right)) {
4832 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004833 spv::Id resultType = builder.getTypeId(right);
4834 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004835 op = spv::OpMatrixTimesScalar;
4836 } else
4837 firstClass = false;
4838 break;
4839 case spv::OpMatrixTimesScalar:
4840 if (builder.isMatrix(right))
4841 std::swap(left, right);
4842 assert(builder.isScalar(right));
4843 break;
4844 case spv::OpVectorTimesMatrix:
4845 assert(builder.isVector(left));
4846 assert(builder.isMatrix(right));
4847 break;
4848 case spv::OpMatrixTimesVector:
4849 assert(builder.isMatrix(left));
4850 assert(builder.isVector(right));
4851 break;
4852 case spv::OpMatrixTimesMatrix:
4853 assert(builder.isMatrix(left));
4854 assert(builder.isMatrix(right));
4855 break;
4856 default:
4857 firstClass = false;
4858 break;
4859 }
4860
qining25262b32016-05-06 17:25:16 -04004861 if (firstClass) {
4862 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004863 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004864 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004865 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004866 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004867
LoopDawg592860c2016-06-09 08:57:35 -06004868 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004869 // The result type of all of them is the same type as the (a) matrix operand.
4870 // The algorithm is to:
4871 // - break the matrix(es) into vectors
4872 // - smear any scalar to a vector
4873 // - do vector operations
4874 // - make a matrix out the vector results
4875 switch (op) {
4876 case spv::OpFAdd:
4877 case spv::OpFSub:
4878 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004879 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004880 case spv::OpFMul:
4881 {
4882 // one time set up...
4883 bool leftMat = builder.isMatrix(left);
4884 bool rightMat = builder.isMatrix(right);
4885 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4886 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4887 spv::Id scalarType = builder.getScalarTypeId(typeId);
4888 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4889 std::vector<spv::Id> results;
4890 spv::Id smearVec = spv::NoResult;
4891 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004892 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004893 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004894 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004895
4896 // do each vector op
4897 for (unsigned int c = 0; c < numCols; ++c) {
4898 std::vector<unsigned int> indexes;
4899 indexes.push_back(c);
4900 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4901 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004902 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004903 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004904 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004905 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004906 }
4907
4908 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004909 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004910 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004911 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004912 }
4913 default:
4914 assert(0);
4915 return spv::NoResult;
4916 }
4917}
4918
John Kessenichead86222018-03-28 18:01:20 -06004919spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4920 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004921{
4922 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004923 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004924 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004925 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4926 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004927
4928 switch (op) {
4929 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004930 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004931 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004932 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004933 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004934 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004935 unaryOp = spv::OpSNegate;
4936 break;
4937
4938 case glslang::EOpLogicalNot:
4939 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004940 unaryOp = spv::OpLogicalNot;
4941 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004942 case glslang::EOpBitwiseNot:
4943 unaryOp = spv::OpNot;
4944 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004945
John Kessenich140f3df2015-06-26 16:58:36 -06004946 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004947 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004948 break;
4949 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004950 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004951 break;
4952 case glslang::EOpTranspose:
4953 unaryOp = spv::OpTranspose;
4954 break;
4955
4956 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004957 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004958 break;
4959 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004960 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004961 break;
4962 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004963 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004964 break;
4965 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004966 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004967 break;
4968 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004969 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004970 break;
4971 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004972 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004973 break;
4974 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004975 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004976 break;
4977 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004978 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004979 break;
4980
4981 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004983 break;
4984 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004985 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004986 break;
4987 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004988 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 break;
4990 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004991 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004992 break;
4993 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004994 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004995 break;
4996 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004997 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004998 break;
4999
5000 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005001 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005002 break;
5003 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005004 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005005 break;
5006
5007 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005008 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005009 break;
5010 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005011 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005012 break;
5013 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005014 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005015 break;
5016 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005017 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005018 break;
5019 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005020 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005021 break;
5022 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005023 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005024 break;
5025
5026 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005027 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005028 break;
5029 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005030 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005031 break;
5032 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005033 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005034 break;
5035 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005036 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005037 break;
5038 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005039 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005040 break;
5041 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005042 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005043 break;
5044
5045 case glslang::EOpIsNan:
5046 unaryOp = spv::OpIsNan;
5047 break;
5048 case glslang::EOpIsInf:
5049 unaryOp = spv::OpIsInf;
5050 break;
LoopDawg592860c2016-06-09 08:57:35 -06005051 case glslang::EOpIsFinite:
5052 unaryOp = spv::OpIsFinite;
5053 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005054
Rex Xucbc426e2015-12-15 16:03:10 +08005055 case glslang::EOpFloatBitsToInt:
5056 case glslang::EOpFloatBitsToUint:
5057 case glslang::EOpIntBitsToFloat:
5058 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005059 case glslang::EOpDoubleBitsToInt64:
5060 case glslang::EOpDoubleBitsToUint64:
5061 case glslang::EOpInt64BitsToDouble:
5062 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005063 case glslang::EOpFloat16BitsToInt16:
5064 case glslang::EOpFloat16BitsToUint16:
5065 case glslang::EOpInt16BitsToFloat16:
5066 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005067 unaryOp = spv::OpBitcast;
5068 break;
5069
John Kessenich140f3df2015-06-26 16:58:36 -06005070 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005071 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005072 break;
5073 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005074 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005075 break;
5076 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005077 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005078 break;
5079 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005080 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005081 break;
5082 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005083 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005084 break;
5085 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005086 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005087 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005088 case glslang::EOpPackSnorm4x8:
5089 libCall = spv::GLSLstd450PackSnorm4x8;
5090 break;
5091 case glslang::EOpUnpackSnorm4x8:
5092 libCall = spv::GLSLstd450UnpackSnorm4x8;
5093 break;
5094 case glslang::EOpPackUnorm4x8:
5095 libCall = spv::GLSLstd450PackUnorm4x8;
5096 break;
5097 case glslang::EOpUnpackUnorm4x8:
5098 libCall = spv::GLSLstd450UnpackUnorm4x8;
5099 break;
5100 case glslang::EOpPackDouble2x32:
5101 libCall = spv::GLSLstd450PackDouble2x32;
5102 break;
5103 case glslang::EOpUnpackDouble2x32:
5104 libCall = spv::GLSLstd450UnpackDouble2x32;
5105 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005106
Rex Xu8ff43de2016-04-22 16:51:45 +08005107 case glslang::EOpPackInt2x32:
5108 case glslang::EOpUnpackInt2x32:
5109 case glslang::EOpPackUint2x32:
5110 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005111 case glslang::EOpPack16:
5112 case glslang::EOpPack32:
5113 case glslang::EOpPack64:
5114 case glslang::EOpUnpack32:
5115 case glslang::EOpUnpack16:
5116 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005117 case glslang::EOpPackInt2x16:
5118 case glslang::EOpUnpackInt2x16:
5119 case glslang::EOpPackUint2x16:
5120 case glslang::EOpUnpackUint2x16:
5121 case glslang::EOpPackInt4x16:
5122 case glslang::EOpUnpackInt4x16:
5123 case glslang::EOpPackUint4x16:
5124 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005125 case glslang::EOpPackFloat2x16:
5126 case glslang::EOpUnpackFloat2x16:
5127 unaryOp = spv::OpBitcast;
5128 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005129
John Kessenich140f3df2015-06-26 16:58:36 -06005130 case glslang::EOpDPdx:
5131 unaryOp = spv::OpDPdx;
5132 break;
5133 case glslang::EOpDPdy:
5134 unaryOp = spv::OpDPdy;
5135 break;
5136 case glslang::EOpFwidth:
5137 unaryOp = spv::OpFwidth;
5138 break;
5139 case glslang::EOpDPdxFine:
5140 unaryOp = spv::OpDPdxFine;
5141 break;
5142 case glslang::EOpDPdyFine:
5143 unaryOp = spv::OpDPdyFine;
5144 break;
5145 case glslang::EOpFwidthFine:
5146 unaryOp = spv::OpFwidthFine;
5147 break;
5148 case glslang::EOpDPdxCoarse:
5149 unaryOp = spv::OpDPdxCoarse;
5150 break;
5151 case glslang::EOpDPdyCoarse:
5152 unaryOp = spv::OpDPdyCoarse;
5153 break;
5154 case glslang::EOpFwidthCoarse:
5155 unaryOp = spv::OpFwidthCoarse;
5156 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005157 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005158#ifdef AMD_EXTENSIONS
5159 if (typeProxy == glslang::EbtFloat16)
5160 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5161#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005162 libCall = spv::GLSLstd450InterpolateAtCentroid;
5163 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 case glslang::EOpAny:
5165 unaryOp = spv::OpAny;
5166 break;
5167 case glslang::EOpAll:
5168 unaryOp = spv::OpAll;
5169 break;
5170
5171 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005172 if (isFloat)
5173 libCall = spv::GLSLstd450FAbs;
5174 else
5175 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005176 break;
5177 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005178 if (isFloat)
5179 libCall = spv::GLSLstd450FSign;
5180 else
5181 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183
John Kessenichfc51d282015-08-19 13:34:18 -06005184 case glslang::EOpAtomicCounterIncrement:
5185 case glslang::EOpAtomicCounterDecrement:
5186 case glslang::EOpAtomicCounter:
5187 {
5188 // Handle all of the atomics in one place, in createAtomicOperation()
5189 std::vector<spv::Id> operands;
5190 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005191 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005192 }
5193
John Kessenichfc51d282015-08-19 13:34:18 -06005194 case glslang::EOpBitFieldReverse:
5195 unaryOp = spv::OpBitReverse;
5196 break;
5197 case glslang::EOpBitCount:
5198 unaryOp = spv::OpBitCount;
5199 break;
5200 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005201 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005202 break;
5203 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005204 if (isUnsigned)
5205 libCall = spv::GLSLstd450FindUMsb;
5206 else
5207 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005208 break;
5209
Rex Xu574ab042016-04-14 16:53:07 +08005210 case glslang::EOpBallot:
5211 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005212 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005213 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005214 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005215#ifdef AMD_EXTENSIONS
5216 case glslang::EOpMinInvocations:
5217 case glslang::EOpMaxInvocations:
5218 case glslang::EOpAddInvocations:
5219 case glslang::EOpMinInvocationsNonUniform:
5220 case glslang::EOpMaxInvocationsNonUniform:
5221 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005222 case glslang::EOpMinInvocationsInclusiveScan:
5223 case glslang::EOpMaxInvocationsInclusiveScan:
5224 case glslang::EOpAddInvocationsInclusiveScan:
5225 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5226 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5227 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5228 case glslang::EOpMinInvocationsExclusiveScan:
5229 case glslang::EOpMaxInvocationsExclusiveScan:
5230 case glslang::EOpAddInvocationsExclusiveScan:
5231 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5232 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5233 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005234#endif
Rex Xu51596642016-09-21 18:56:12 +08005235 {
5236 std::vector<spv::Id> operands;
5237 operands.push_back(operand);
5238 return createInvocationsOperation(op, typeId, operands, typeProxy);
5239 }
John Kessenich66011cb2018-03-06 16:12:04 -07005240 case glslang::EOpSubgroupAll:
5241 case glslang::EOpSubgroupAny:
5242 case glslang::EOpSubgroupAllEqual:
5243 case glslang::EOpSubgroupBroadcastFirst:
5244 case glslang::EOpSubgroupBallot:
5245 case glslang::EOpSubgroupInverseBallot:
5246 case glslang::EOpSubgroupBallotBitCount:
5247 case glslang::EOpSubgroupBallotInclusiveBitCount:
5248 case glslang::EOpSubgroupBallotExclusiveBitCount:
5249 case glslang::EOpSubgroupBallotFindLSB:
5250 case glslang::EOpSubgroupBallotFindMSB:
5251 case glslang::EOpSubgroupAdd:
5252 case glslang::EOpSubgroupMul:
5253 case glslang::EOpSubgroupMin:
5254 case glslang::EOpSubgroupMax:
5255 case glslang::EOpSubgroupAnd:
5256 case glslang::EOpSubgroupOr:
5257 case glslang::EOpSubgroupXor:
5258 case glslang::EOpSubgroupInclusiveAdd:
5259 case glslang::EOpSubgroupInclusiveMul:
5260 case glslang::EOpSubgroupInclusiveMin:
5261 case glslang::EOpSubgroupInclusiveMax:
5262 case glslang::EOpSubgroupInclusiveAnd:
5263 case glslang::EOpSubgroupInclusiveOr:
5264 case glslang::EOpSubgroupInclusiveXor:
5265 case glslang::EOpSubgroupExclusiveAdd:
5266 case glslang::EOpSubgroupExclusiveMul:
5267 case glslang::EOpSubgroupExclusiveMin:
5268 case glslang::EOpSubgroupExclusiveMax:
5269 case glslang::EOpSubgroupExclusiveAnd:
5270 case glslang::EOpSubgroupExclusiveOr:
5271 case glslang::EOpSubgroupExclusiveXor:
5272 case glslang::EOpSubgroupQuadSwapHorizontal:
5273 case glslang::EOpSubgroupQuadSwapVertical:
5274 case glslang::EOpSubgroupQuadSwapDiagonal: {
5275 std::vector<spv::Id> operands;
5276 operands.push_back(operand);
5277 return createSubgroupOperation(op, typeId, operands, typeProxy);
5278 }
Rex Xu9d93a232016-05-05 12:30:44 +08005279#ifdef AMD_EXTENSIONS
5280 case glslang::EOpMbcnt:
5281 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5282 libCall = spv::MbcntAMD;
5283 break;
5284
5285 case glslang::EOpCubeFaceIndex:
5286 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5287 libCall = spv::CubeFaceIndexAMD;
5288 break;
5289
5290 case glslang::EOpCubeFaceCoord:
5291 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5292 libCall = spv::CubeFaceCoordAMD;
5293 break;
5294#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005295#ifdef NV_EXTENSIONS
5296 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005297 unaryOp = spv::OpGroupNonUniformPartitionNV;
5298 break;
5299#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005300 default:
5301 return 0;
5302 }
5303
5304 spv::Id id;
5305 if (libCall >= 0) {
5306 std::vector<spv::Id> args;
5307 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005308 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005309 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005310 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005311 }
John Kessenich140f3df2015-06-26 16:58:36 -06005312
John Kessenichead86222018-03-28 18:01:20 -06005313 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005314 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005315 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005316}
5317
John Kessenich7a53f762016-01-20 11:19:27 -07005318// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005319spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5320 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005321{
5322 // Handle unary operations vector by vector.
5323 // The result type is the same type as the original type.
5324 // The algorithm is to:
5325 // - break the matrix into vectors
5326 // - apply the operation to each vector
5327 // - make a matrix out the vector results
5328
5329 // get the types sorted out
5330 int numCols = builder.getNumColumns(operand);
5331 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005332 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5333 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005334 std::vector<spv::Id> results;
5335
5336 // do each vector op
5337 for (int c = 0; c < numCols; ++c) {
5338 std::vector<unsigned int> indexes;
5339 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005340 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5341 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005342 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005343 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005344 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005345 }
5346
5347 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005348 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005349 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005350 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005351}
5352
John Kessenichad7645f2018-06-04 19:11:25 -06005353// For converting integers where both the bitwidth and the signedness could
5354// change, but only do the width change here. The caller is still responsible
5355// for the signedness conversion.
5356spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005357{
John Kessenichad7645f2018-06-04 19:11:25 -06005358 // Get the result type width, based on the type to convert to.
5359 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005360 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005361 case glslang::EOpConvInt16ToUint8:
5362 case glslang::EOpConvIntToUint8:
5363 case glslang::EOpConvInt64ToUint8:
5364 case glslang::EOpConvUint16ToInt8:
5365 case glslang::EOpConvUintToInt8:
5366 case glslang::EOpConvUint64ToInt8:
5367 width = 8;
5368 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005369 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005370 case glslang::EOpConvIntToUint16:
5371 case glslang::EOpConvInt64ToUint16:
5372 case glslang::EOpConvUint8ToInt16:
5373 case glslang::EOpConvUintToInt16:
5374 case glslang::EOpConvUint64ToInt16:
5375 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005376 break;
5377 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005378 case glslang::EOpConvInt16ToUint:
5379 case glslang::EOpConvInt64ToUint:
5380 case glslang::EOpConvUint8ToInt:
5381 case glslang::EOpConvUint16ToInt:
5382 case glslang::EOpConvUint64ToInt:
5383 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005384 break;
5385 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005386 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005387 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005388 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005389 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005390 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005391 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005392 break;
5393
5394 default:
5395 assert(false && "Default missing");
5396 break;
5397 }
5398
John Kessenichad7645f2018-06-04 19:11:25 -06005399 // Get the conversion operation and result type,
5400 // based on the target width, but the source type.
5401 spv::Id type = spv::NoType;
5402 spv::Op convOp = spv::OpNop;
5403 switch(op) {
5404 case glslang::EOpConvInt8ToUint16:
5405 case glslang::EOpConvInt8ToUint:
5406 case glslang::EOpConvInt8ToUint64:
5407 case glslang::EOpConvInt16ToUint8:
5408 case glslang::EOpConvInt16ToUint:
5409 case glslang::EOpConvInt16ToUint64:
5410 case glslang::EOpConvIntToUint8:
5411 case glslang::EOpConvIntToUint16:
5412 case glslang::EOpConvIntToUint64:
5413 case glslang::EOpConvInt64ToUint8:
5414 case glslang::EOpConvInt64ToUint16:
5415 case glslang::EOpConvInt64ToUint:
5416 convOp = spv::OpSConvert;
5417 type = builder.makeIntType(width);
5418 break;
5419 default:
5420 convOp = spv::OpUConvert;
5421 type = builder.makeUintType(width);
5422 break;
5423 }
5424
John Kessenich66011cb2018-03-06 16:12:04 -07005425 if (vectorSize > 0)
5426 type = builder.makeVectorType(type, vectorSize);
5427
John Kessenichad7645f2018-06-04 19:11:25 -06005428 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005429}
5430
John Kessenichead86222018-03-28 18:01:20 -06005431spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5432 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005433{
5434 spv::Op convOp = spv::OpNop;
5435 spv::Id zero = 0;
5436 spv::Id one = 0;
5437
5438 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5439
5440 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005441 case glslang::EOpConvInt8ToBool:
5442 case glslang::EOpConvUint8ToBool:
5443 zero = builder.makeUint8Constant(0);
5444 zero = makeSmearedConstant(zero, vectorSize);
5445 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005446 case glslang::EOpConvInt16ToBool:
5447 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005448 zero = builder.makeUint16Constant(0);
5449 zero = makeSmearedConstant(zero, vectorSize);
5450 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5451 case glslang::EOpConvIntToBool:
5452 case glslang::EOpConvUintToBool:
5453 zero = builder.makeUintConstant(0);
5454 zero = makeSmearedConstant(zero, vectorSize);
5455 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5456 case glslang::EOpConvInt64ToBool:
5457 case glslang::EOpConvUint64ToBool:
5458 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005459 zero = makeSmearedConstant(zero, vectorSize);
5460 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5461
5462 case glslang::EOpConvFloatToBool:
5463 zero = builder.makeFloatConstant(0.0F);
5464 zero = makeSmearedConstant(zero, vectorSize);
5465 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5466
5467 case glslang::EOpConvDoubleToBool:
5468 zero = builder.makeDoubleConstant(0.0);
5469 zero = makeSmearedConstant(zero, vectorSize);
5470 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5471
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005472 case glslang::EOpConvFloat16ToBool:
5473 zero = builder.makeFloat16Constant(0.0F);
5474 zero = makeSmearedConstant(zero, vectorSize);
5475 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005476
John Kessenich140f3df2015-06-26 16:58:36 -06005477 case glslang::EOpConvBoolToFloat:
5478 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005479 zero = builder.makeFloatConstant(0.0F);
5480 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005482
John Kessenich140f3df2015-06-26 16:58:36 -06005483 case glslang::EOpConvBoolToDouble:
5484 convOp = spv::OpSelect;
5485 zero = builder.makeDoubleConstant(0.0);
5486 one = builder.makeDoubleConstant(1.0);
5487 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005488
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005489 case glslang::EOpConvBoolToFloat16:
5490 convOp = spv::OpSelect;
5491 zero = builder.makeFloat16Constant(0.0F);
5492 one = builder.makeFloat16Constant(1.0F);
5493 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005494
5495 case glslang::EOpConvBoolToInt8:
5496 zero = builder.makeInt8Constant(0);
5497 one = builder.makeInt8Constant(1);
5498 convOp = spv::OpSelect;
5499 break;
5500
5501 case glslang::EOpConvBoolToUint8:
5502 zero = builder.makeUint8Constant(0);
5503 one = builder.makeUint8Constant(1);
5504 convOp = spv::OpSelect;
5505 break;
5506
5507 case glslang::EOpConvBoolToInt16:
5508 zero = builder.makeInt16Constant(0);
5509 one = builder.makeInt16Constant(1);
5510 convOp = spv::OpSelect;
5511 break;
5512
5513 case glslang::EOpConvBoolToUint16:
5514 zero = builder.makeUint16Constant(0);
5515 one = builder.makeUint16Constant(1);
5516 convOp = spv::OpSelect;
5517 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005518
John Kessenich140f3df2015-06-26 16:58:36 -06005519 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005520 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005521 if (op == glslang::EOpConvBoolToInt64)
5522 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005523 else
5524 zero = builder.makeIntConstant(0);
5525
5526 if (op == glslang::EOpConvBoolToInt64)
5527 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005528 else
5529 one = builder.makeIntConstant(1);
5530
John Kessenich140f3df2015-06-26 16:58:36 -06005531 convOp = spv::OpSelect;
5532 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005533
John Kessenich140f3df2015-06-26 16:58:36 -06005534 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005535 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005536 if (op == glslang::EOpConvBoolToUint64)
5537 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005538 else
5539 zero = builder.makeUintConstant(0);
5540
5541 if (op == glslang::EOpConvBoolToUint64)
5542 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005543 else
5544 one = builder.makeUintConstant(1);
5545
John Kessenich140f3df2015-06-26 16:58:36 -06005546 convOp = spv::OpSelect;
5547 break;
5548
John Kessenich66011cb2018-03-06 16:12:04 -07005549 case glslang::EOpConvInt8ToFloat16:
5550 case glslang::EOpConvInt8ToFloat:
5551 case glslang::EOpConvInt8ToDouble:
5552 case glslang::EOpConvInt16ToFloat16:
5553 case glslang::EOpConvInt16ToFloat:
5554 case glslang::EOpConvInt16ToDouble:
5555 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005556 case glslang::EOpConvIntToFloat:
5557 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005558 case glslang::EOpConvInt64ToFloat:
5559 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005560 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005561 convOp = spv::OpConvertSToF;
5562 break;
5563
John Kessenich66011cb2018-03-06 16:12:04 -07005564 case glslang::EOpConvUint8ToFloat16:
5565 case glslang::EOpConvUint8ToFloat:
5566 case glslang::EOpConvUint8ToDouble:
5567 case glslang::EOpConvUint16ToFloat16:
5568 case glslang::EOpConvUint16ToFloat:
5569 case glslang::EOpConvUint16ToDouble:
5570 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005571 case glslang::EOpConvUintToFloat:
5572 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005573 case glslang::EOpConvUint64ToFloat:
5574 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005575 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005576 convOp = spv::OpConvertUToF;
5577 break;
5578
5579 case glslang::EOpConvDoubleToFloat:
5580 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005581 case glslang::EOpConvDoubleToFloat16:
5582 case glslang::EOpConvFloat16ToDouble:
5583 case glslang::EOpConvFloatToFloat16:
5584 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005585 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005586 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005587 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005588 break;
5589
John Kessenich66011cb2018-03-06 16:12:04 -07005590 case glslang::EOpConvFloat16ToInt8:
5591 case glslang::EOpConvFloatToInt8:
5592 case glslang::EOpConvDoubleToInt8:
5593 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005594 case glslang::EOpConvFloatToInt16:
5595 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005596 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005597 case glslang::EOpConvFloatToInt:
5598 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005599 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005600 case glslang::EOpConvFloatToInt64:
5601 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005602 convOp = spv::OpConvertFToS;
5603 break;
5604
John Kessenich66011cb2018-03-06 16:12:04 -07005605 case glslang::EOpConvUint8ToInt8:
5606 case glslang::EOpConvInt8ToUint8:
5607 case glslang::EOpConvUint16ToInt16:
5608 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005609 case glslang::EOpConvUintToInt:
5610 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005611 case glslang::EOpConvUint64ToInt64:
5612 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005613 if (builder.isInSpecConstCodeGenMode()) {
5614 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005615 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5616 zero = builder.makeUint8Constant(0);
5617 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005618 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005619 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5620 zero = builder.makeUint64Constant(0);
5621 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005622 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005623 }
qining189b2032016-04-12 23:16:20 -04005624 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005625 // Use OpIAdd, instead of OpBitcast to do the conversion when
5626 // generating for OpSpecConstantOp instruction.
5627 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5628 }
5629 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005630 convOp = spv::OpBitcast;
5631 break;
5632
John Kessenich66011cb2018-03-06 16:12:04 -07005633 case glslang::EOpConvFloat16ToUint8:
5634 case glslang::EOpConvFloatToUint8:
5635 case glslang::EOpConvDoubleToUint8:
5636 case glslang::EOpConvFloat16ToUint16:
5637 case glslang::EOpConvFloatToUint16:
5638 case glslang::EOpConvDoubleToUint16:
5639 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005640 case glslang::EOpConvFloatToUint:
5641 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005642 case glslang::EOpConvFloatToUint64:
5643 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005644 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005645 convOp = spv::OpConvertFToU;
5646 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005647
John Kessenich66011cb2018-03-06 16:12:04 -07005648 case glslang::EOpConvInt8ToInt16:
5649 case glslang::EOpConvInt8ToInt:
5650 case glslang::EOpConvInt8ToInt64:
5651 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005652 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005653 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005654 case glslang::EOpConvIntToInt8:
5655 case glslang::EOpConvIntToInt16:
5656 case glslang::EOpConvIntToInt64:
5657 case glslang::EOpConvInt64ToInt8:
5658 case glslang::EOpConvInt64ToInt16:
5659 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005660 convOp = spv::OpSConvert;
5661 break;
5662
John Kessenich66011cb2018-03-06 16:12:04 -07005663 case glslang::EOpConvUint8ToUint16:
5664 case glslang::EOpConvUint8ToUint:
5665 case glslang::EOpConvUint8ToUint64:
5666 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005667 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005668 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005669 case glslang::EOpConvUintToUint8:
5670 case glslang::EOpConvUintToUint16:
5671 case glslang::EOpConvUintToUint64:
5672 case glslang::EOpConvUint64ToUint8:
5673 case glslang::EOpConvUint64ToUint16:
5674 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005675 convOp = spv::OpUConvert;
5676 break;
5677
John Kessenich66011cb2018-03-06 16:12:04 -07005678 case glslang::EOpConvInt8ToUint16:
5679 case glslang::EOpConvInt8ToUint:
5680 case glslang::EOpConvInt8ToUint64:
5681 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005682 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005683 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005684 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005685 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005686 case glslang::EOpConvIntToUint64:
5687 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005688 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005689 case glslang::EOpConvInt64ToUint:
5690 case glslang::EOpConvUint8ToInt16:
5691 case glslang::EOpConvUint8ToInt:
5692 case glslang::EOpConvUint8ToInt64:
5693 case glslang::EOpConvUint16ToInt8:
5694 case glslang::EOpConvUint16ToInt:
5695 case glslang::EOpConvUint16ToInt64:
5696 case glslang::EOpConvUintToInt8:
5697 case glslang::EOpConvUintToInt16:
5698 case glslang::EOpConvUintToInt64:
5699 case glslang::EOpConvUint64ToInt8:
5700 case glslang::EOpConvUint64ToInt16:
5701 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005702 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005703 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005704
5705 if (builder.isInSpecConstCodeGenMode()) {
5706 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005707 switch(op) {
5708 case glslang::EOpConvInt16ToUint8:
5709 case glslang::EOpConvIntToUint8:
5710 case glslang::EOpConvInt64ToUint8:
5711 case glslang::EOpConvUint16ToInt8:
5712 case glslang::EOpConvUintToInt8:
5713 case glslang::EOpConvUint64ToInt8:
5714 zero = builder.makeUint8Constant(0);
5715 break;
5716 case glslang::EOpConvInt8ToUint16:
5717 case glslang::EOpConvIntToUint16:
5718 case glslang::EOpConvInt64ToUint16:
5719 case glslang::EOpConvUint8ToInt16:
5720 case glslang::EOpConvUintToInt16:
5721 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005722 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005723 break;
5724 case glslang::EOpConvInt8ToUint:
5725 case glslang::EOpConvInt16ToUint:
5726 case glslang::EOpConvInt64ToUint:
5727 case glslang::EOpConvUint8ToInt:
5728 case glslang::EOpConvUint16ToInt:
5729 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005730 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005731 break;
5732 case glslang::EOpConvInt8ToUint64:
5733 case glslang::EOpConvInt16ToUint64:
5734 case glslang::EOpConvIntToUint64:
5735 case glslang::EOpConvUint8ToInt64:
5736 case glslang::EOpConvUint16ToInt64:
5737 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005738 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005739 break;
5740 default:
5741 assert(false && "Default missing");
5742 break;
5743 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005744 zero = makeSmearedConstant(zero, vectorSize);
5745 // Use OpIAdd, instead of OpBitcast to do the conversion when
5746 // generating for OpSpecConstantOp instruction.
5747 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5748 }
5749 // For normal run-time conversion instruction, use OpBitcast.
5750 convOp = spv::OpBitcast;
5751 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005752 default:
5753 break;
5754 }
5755
5756 spv::Id result = 0;
5757 if (convOp == spv::OpNop)
5758 return result;
5759
5760 if (convOp == spv::OpSelect) {
5761 zero = makeSmearedConstant(zero, vectorSize);
5762 one = makeSmearedConstant(one, vectorSize);
5763 result = builder.createTriOp(convOp, destType, operand, one, zero);
5764 } else
5765 result = builder.createUnaryOp(convOp, destType, operand);
5766
John Kessenichead86222018-03-28 18:01:20 -06005767 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005768 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005769 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005770}
5771
5772spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5773{
5774 if (vectorSize == 0)
5775 return constant;
5776
5777 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5778 std::vector<spv::Id> components;
5779 for (int c = 0; c < vectorSize; ++c)
5780 components.push_back(constant);
5781 return builder.makeCompositeConstant(vectorTypeId, components);
5782}
5783
John Kessenich426394d2015-07-23 10:22:48 -06005784// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005785spv::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 -06005786{
5787 spv::Op opCode = spv::OpNop;
5788
5789 switch (op) {
5790 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005791 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005792 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005793 opCode = spv::OpAtomicIAdd;
5794 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005795 case glslang::EOpAtomicCounterSubtract:
5796 opCode = spv::OpAtomicISub;
5797 break;
John Kessenich426394d2015-07-23 10:22:48 -06005798 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005799 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005800 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005801 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005802 break;
5803 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005804 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005805 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005806 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005807 break;
5808 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005809 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005810 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005811 opCode = spv::OpAtomicAnd;
5812 break;
5813 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005814 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005815 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005816 opCode = spv::OpAtomicOr;
5817 break;
5818 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005819 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005820 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005821 opCode = spv::OpAtomicXor;
5822 break;
5823 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005824 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005825 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005826 opCode = spv::OpAtomicExchange;
5827 break;
5828 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005829 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005830 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005831 opCode = spv::OpAtomicCompareExchange;
5832 break;
5833 case glslang::EOpAtomicCounterIncrement:
5834 opCode = spv::OpAtomicIIncrement;
5835 break;
5836 case glslang::EOpAtomicCounterDecrement:
5837 opCode = spv::OpAtomicIDecrement;
5838 break;
5839 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005840 case glslang::EOpImageAtomicLoad:
5841 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005842 opCode = spv::OpAtomicLoad;
5843 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005844 case glslang::EOpAtomicStore:
5845 case glslang::EOpImageAtomicStore:
5846 opCode = spv::OpAtomicStore;
5847 break;
John Kessenich426394d2015-07-23 10:22:48 -06005848 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005849 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005850 break;
5851 }
5852
Rex Xue8fe8b02017-09-26 15:42:56 +08005853 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5854 builder.addCapability(spv::CapabilityInt64Atomics);
5855
John Kessenich426394d2015-07-23 10:22:48 -06005856 // Sort out the operands
5857 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005858 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005859 // - compare-exchange swaps the value and comparator
5860 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005861 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005862 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5863 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5864 spv::Id scopeId;
5865 if (glslangIntermediate->usingVulkanMemoryModel()) {
5866 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5867 } else {
5868 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5869 }
5870 // semantics default to relaxed
5871 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5872 spv::Id semanticsId2 = semanticsId;
5873
5874 pointerId = operands[0];
5875 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5876 // no additional operands
5877 } else if (opCode == spv::OpAtomicCompareExchange) {
5878 compareId = operands[1];
5879 valueId = operands[2];
5880 if (operands.size() > 3) {
5881 scopeId = operands[3];
5882 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5883 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5884 }
5885 } else if (opCode == spv::OpAtomicLoad) {
5886 if (operands.size() > 1) {
5887 scopeId = operands[1];
5888 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5889 }
5890 } else {
5891 // atomic store or RMW
5892 valueId = operands[1];
5893 if (operands.size() > 2) {
5894 scopeId = operands[2];
5895 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5896 }
Rex Xu04db3f52015-09-16 11:44:02 +08005897 }
John Kessenich426394d2015-07-23 10:22:48 -06005898
Jeff Bolz36831c92018-09-05 10:11:41 -05005899 // Check for capabilities
5900 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5901 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5902 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5903 }
John Kessenich426394d2015-07-23 10:22:48 -06005904
Jeff Bolz36831c92018-09-05 10:11:41 -05005905 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5906 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5907 }
John Kessenich48d6e792017-10-06 21:21:48 -06005908
Jeff Bolz36831c92018-09-05 10:11:41 -05005909 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5910 spvAtomicOperands.push_back(pointerId);
5911 spvAtomicOperands.push_back(scopeId);
5912 spvAtomicOperands.push_back(semanticsId);
5913 if (opCode == spv::OpAtomicCompareExchange) {
5914 spvAtomicOperands.push_back(semanticsId2);
5915 spvAtomicOperands.push_back(valueId);
5916 spvAtomicOperands.push_back(compareId);
5917 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5918 spvAtomicOperands.push_back(valueId);
5919 }
John Kessenich48d6e792017-10-06 21:21:48 -06005920
Jeff Bolz36831c92018-09-05 10:11:41 -05005921 if (opCode == spv::OpAtomicStore) {
5922 builder.createNoResultOp(opCode, spvAtomicOperands);
5923 return 0;
5924 } else {
5925 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5926
5927 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5928 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5929 if (op == glslang::EOpAtomicCounterDecrement)
5930 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5931
5932 return resultId;
5933 }
John Kessenich426394d2015-07-23 10:22:48 -06005934}
5935
John Kessenich91cef522016-05-05 16:45:40 -06005936// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005937spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005938{
Corentin Walleze7061422018-08-08 15:20:15 +02005939#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005940 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5941 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005942#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005943
Rex Xu51596642016-09-21 18:56:12 +08005944 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005945 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005946 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5947
chaocf200da82016-12-20 12:44:35 -08005948 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5949 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005950 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5951 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005952 } else if (op == glslang::EOpAnyInvocation ||
5953 op == glslang::EOpAllInvocations ||
5954 op == glslang::EOpAllInvocationsEqual) {
5955 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5956 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005957 } else {
5958 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005959#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005960 if (op == glslang::EOpMinInvocationsNonUniform ||
5961 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005962 op == glslang::EOpAddInvocationsNonUniform ||
5963 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5964 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5965 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5966 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5967 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5968 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005969 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005970#endif
Rex Xu51596642016-09-21 18:56:12 +08005971
Rex Xu9d93a232016-05-05 12:30:44 +08005972#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005973 switch (op) {
5974 case glslang::EOpMinInvocations:
5975 case glslang::EOpMaxInvocations:
5976 case glslang::EOpAddInvocations:
5977 case glslang::EOpMinInvocationsNonUniform:
5978 case glslang::EOpMaxInvocationsNonUniform:
5979 case glslang::EOpAddInvocationsNonUniform:
5980 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005981 break;
5982 case glslang::EOpMinInvocationsInclusiveScan:
5983 case glslang::EOpMaxInvocationsInclusiveScan:
5984 case glslang::EOpAddInvocationsInclusiveScan:
5985 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5986 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5987 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5988 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005989 break;
5990 case glslang::EOpMinInvocationsExclusiveScan:
5991 case glslang::EOpMaxInvocationsExclusiveScan:
5992 case glslang::EOpAddInvocationsExclusiveScan:
5993 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5994 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5995 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5996 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005997 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005998 default:
5999 break;
Rex Xu430ef402016-10-14 17:22:23 +08006000 }
John Kessenich149afc32018-08-14 13:31:43 -06006001 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6002 spvGroupOperands.push_back(scope);
6003 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006004 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006005 spvGroupOperands.push_back(groupOp);
6006 }
Rex Xu9d93a232016-05-05 12:30:44 +08006007#endif
Rex Xu51596642016-09-21 18:56:12 +08006008 }
6009
John Kessenich149afc32018-08-14 13:31:43 -06006010 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6011 spv::IdImmediate op = { true, *opIt };
6012 spvGroupOperands.push_back(op);
6013 }
John Kessenich91cef522016-05-05 16:45:40 -06006014
6015 switch (op) {
6016 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006017 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006018 break;
John Kessenich91cef522016-05-05 16:45:40 -06006019 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006020 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006021 break;
John Kessenich91cef522016-05-05 16:45:40 -06006022 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006023 opCode = spv::OpSubgroupAllEqualKHR;
6024 break;
Rex Xu51596642016-09-21 18:56:12 +08006025 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006026 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006027 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006028 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006029 break;
6030 case glslang::EOpReadFirstInvocation:
6031 opCode = spv::OpSubgroupFirstInvocationKHR;
6032 break;
6033 case glslang::EOpBallot:
6034 {
6035 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6036 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6037 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6038 //
6039 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6040 //
6041 spv::Id uintType = builder.makeUintType(32);
6042 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6043 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6044
6045 std::vector<spv::Id> components;
6046 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6047 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6048
6049 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6050 return builder.createUnaryOp(spv::OpBitcast, typeId,
6051 builder.createCompositeConstruct(uvec2Type, components));
6052 }
6053
Rex Xu9d93a232016-05-05 12:30:44 +08006054#ifdef AMD_EXTENSIONS
6055 case glslang::EOpMinInvocations:
6056 case glslang::EOpMaxInvocations:
6057 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006058 case glslang::EOpMinInvocationsInclusiveScan:
6059 case glslang::EOpMaxInvocationsInclusiveScan:
6060 case glslang::EOpAddInvocationsInclusiveScan:
6061 case glslang::EOpMinInvocationsExclusiveScan:
6062 case glslang::EOpMaxInvocationsExclusiveScan:
6063 case glslang::EOpAddInvocationsExclusiveScan:
6064 if (op == glslang::EOpMinInvocations ||
6065 op == glslang::EOpMinInvocationsInclusiveScan ||
6066 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006067 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006068 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006069 else {
6070 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006071 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006072 else
Rex Xu51596642016-09-21 18:56:12 +08006073 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006074 }
Rex Xu430ef402016-10-14 17:22:23 +08006075 } else if (op == glslang::EOpMaxInvocations ||
6076 op == glslang::EOpMaxInvocationsInclusiveScan ||
6077 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006078 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006079 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006080 else {
6081 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006082 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006083 else
Rex Xu51596642016-09-21 18:56:12 +08006084 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006085 }
6086 } else {
6087 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006088 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006089 else
Rex Xu51596642016-09-21 18:56:12 +08006090 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006091 }
6092
Rex Xu2bbbe062016-08-23 15:41:05 +08006093 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006094 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006095
6096 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006097 case glslang::EOpMinInvocationsNonUniform:
6098 case glslang::EOpMaxInvocationsNonUniform:
6099 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006100 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6101 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6102 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6103 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6104 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6105 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6106 if (op == glslang::EOpMinInvocationsNonUniform ||
6107 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6108 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006109 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006110 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006111 else {
6112 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006113 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006114 else
Rex Xu51596642016-09-21 18:56:12 +08006115 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006116 }
6117 }
Rex Xu430ef402016-10-14 17:22:23 +08006118 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6119 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6120 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006121 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006122 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006123 else {
6124 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006125 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006126 else
Rex Xu51596642016-09-21 18:56:12 +08006127 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006128 }
6129 }
6130 else {
6131 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006132 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006133 else
Rex Xu51596642016-09-21 18:56:12 +08006134 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006135 }
6136
Rex Xu2bbbe062016-08-23 15:41:05 +08006137 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006138 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006139
6140 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006141#endif
John Kessenich91cef522016-05-05 16:45:40 -06006142 default:
6143 logger->missingFunctionality("invocation operation");
6144 return spv::NoResult;
6145 }
Rex Xu51596642016-09-21 18:56:12 +08006146
6147 assert(opCode != spv::OpNop);
6148 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006149}
6150
Rex Xu2bbbe062016-08-23 15:41:05 +08006151// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006152spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6153 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006154{
Rex Xub7072052016-09-26 15:53:40 +08006155#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006156 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6157 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006158 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006159 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006160 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6161 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6162 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006163#else
6164 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6165 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006166 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6167 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006168#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006169
6170 // Handle group invocation operations scalar by scalar.
6171 // The result type is the same type as the original type.
6172 // The algorithm is to:
6173 // - break the vector into scalars
6174 // - apply the operation to each scalar
6175 // - make a vector out the scalar results
6176
6177 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006178 int numComponents = builder.getNumComponents(operands[0]);
6179 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006180 std::vector<spv::Id> results;
6181
6182 // do each scalar op
6183 for (int comp = 0; comp < numComponents; ++comp) {
6184 std::vector<unsigned int> indexes;
6185 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006186 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6187 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006188 if (op == spv::OpSubgroupReadInvocationKHR) {
6189 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006190 spv::IdImmediate operand = { true, operands[1] };
6191 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006192 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006193 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6194 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006195 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006196 spv::IdImmediate operand = { true, operands[1] };
6197 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006198 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006199 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6200 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006201 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006202 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006203 spvGroupOperands.push_back(scalar);
6204 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006205
Rex Xub7072052016-09-26 15:53:40 +08006206 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006207 }
6208
6209 // put the pieces together
6210 return builder.createCompositeConstruct(typeId, results);
6211}
Rex Xu2bbbe062016-08-23 15:41:05 +08006212
John Kessenich66011cb2018-03-06 16:12:04 -07006213// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006214spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6215 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006216{
6217 // Add the required capabilities.
6218 switch (op) {
6219 case glslang::EOpSubgroupElect:
6220 builder.addCapability(spv::CapabilityGroupNonUniform);
6221 break;
6222 case glslang::EOpSubgroupAll:
6223 case glslang::EOpSubgroupAny:
6224 case glslang::EOpSubgroupAllEqual:
6225 builder.addCapability(spv::CapabilityGroupNonUniform);
6226 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6227 break;
6228 case glslang::EOpSubgroupBroadcast:
6229 case glslang::EOpSubgroupBroadcastFirst:
6230 case glslang::EOpSubgroupBallot:
6231 case glslang::EOpSubgroupInverseBallot:
6232 case glslang::EOpSubgroupBallotBitExtract:
6233 case glslang::EOpSubgroupBallotBitCount:
6234 case glslang::EOpSubgroupBallotInclusiveBitCount:
6235 case glslang::EOpSubgroupBallotExclusiveBitCount:
6236 case glslang::EOpSubgroupBallotFindLSB:
6237 case glslang::EOpSubgroupBallotFindMSB:
6238 builder.addCapability(spv::CapabilityGroupNonUniform);
6239 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6240 break;
6241 case glslang::EOpSubgroupShuffle:
6242 case glslang::EOpSubgroupShuffleXor:
6243 builder.addCapability(spv::CapabilityGroupNonUniform);
6244 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6245 break;
6246 case glslang::EOpSubgroupShuffleUp:
6247 case glslang::EOpSubgroupShuffleDown:
6248 builder.addCapability(spv::CapabilityGroupNonUniform);
6249 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6250 break;
6251 case glslang::EOpSubgroupAdd:
6252 case glslang::EOpSubgroupMul:
6253 case glslang::EOpSubgroupMin:
6254 case glslang::EOpSubgroupMax:
6255 case glslang::EOpSubgroupAnd:
6256 case glslang::EOpSubgroupOr:
6257 case glslang::EOpSubgroupXor:
6258 case glslang::EOpSubgroupInclusiveAdd:
6259 case glslang::EOpSubgroupInclusiveMul:
6260 case glslang::EOpSubgroupInclusiveMin:
6261 case glslang::EOpSubgroupInclusiveMax:
6262 case glslang::EOpSubgroupInclusiveAnd:
6263 case glslang::EOpSubgroupInclusiveOr:
6264 case glslang::EOpSubgroupInclusiveXor:
6265 case glslang::EOpSubgroupExclusiveAdd:
6266 case glslang::EOpSubgroupExclusiveMul:
6267 case glslang::EOpSubgroupExclusiveMin:
6268 case glslang::EOpSubgroupExclusiveMax:
6269 case glslang::EOpSubgroupExclusiveAnd:
6270 case glslang::EOpSubgroupExclusiveOr:
6271 case glslang::EOpSubgroupExclusiveXor:
6272 builder.addCapability(spv::CapabilityGroupNonUniform);
6273 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6274 break;
6275 case glslang::EOpSubgroupClusteredAdd:
6276 case glslang::EOpSubgroupClusteredMul:
6277 case glslang::EOpSubgroupClusteredMin:
6278 case glslang::EOpSubgroupClusteredMax:
6279 case glslang::EOpSubgroupClusteredAnd:
6280 case glslang::EOpSubgroupClusteredOr:
6281 case glslang::EOpSubgroupClusteredXor:
6282 builder.addCapability(spv::CapabilityGroupNonUniform);
6283 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6284 break;
6285 case glslang::EOpSubgroupQuadBroadcast:
6286 case glslang::EOpSubgroupQuadSwapHorizontal:
6287 case glslang::EOpSubgroupQuadSwapVertical:
6288 case glslang::EOpSubgroupQuadSwapDiagonal:
6289 builder.addCapability(spv::CapabilityGroupNonUniform);
6290 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6291 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006292#ifdef NV_EXTENSIONS
6293 case glslang::EOpSubgroupPartitionedAdd:
6294 case glslang::EOpSubgroupPartitionedMul:
6295 case glslang::EOpSubgroupPartitionedMin:
6296 case glslang::EOpSubgroupPartitionedMax:
6297 case glslang::EOpSubgroupPartitionedAnd:
6298 case glslang::EOpSubgroupPartitionedOr:
6299 case glslang::EOpSubgroupPartitionedXor:
6300 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6301 case glslang::EOpSubgroupPartitionedInclusiveMul:
6302 case glslang::EOpSubgroupPartitionedInclusiveMin:
6303 case glslang::EOpSubgroupPartitionedInclusiveMax:
6304 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6305 case glslang::EOpSubgroupPartitionedInclusiveOr:
6306 case glslang::EOpSubgroupPartitionedInclusiveXor:
6307 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6308 case glslang::EOpSubgroupPartitionedExclusiveMul:
6309 case glslang::EOpSubgroupPartitionedExclusiveMin:
6310 case glslang::EOpSubgroupPartitionedExclusiveMax:
6311 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6312 case glslang::EOpSubgroupPartitionedExclusiveOr:
6313 case glslang::EOpSubgroupPartitionedExclusiveXor:
6314 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6315 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6316 break;
6317#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006318 default: assert(0 && "Unhandled subgroup operation!");
6319 }
6320
6321 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6322 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6323 const bool isBool = typeProxy == glslang::EbtBool;
6324
6325 spv::Op opCode = spv::OpNop;
6326
6327 // Figure out which opcode to use.
6328 switch (op) {
6329 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6330 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6331 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6332 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6333 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6334 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6335 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6336 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6337 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6338 case glslang::EOpSubgroupBallotBitCount:
6339 case glslang::EOpSubgroupBallotInclusiveBitCount:
6340 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6341 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6342 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6343 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6344 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6345 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6346 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6347 case glslang::EOpSubgroupAdd:
6348 case glslang::EOpSubgroupInclusiveAdd:
6349 case glslang::EOpSubgroupExclusiveAdd:
6350 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006351#ifdef NV_EXTENSIONS
6352 case glslang::EOpSubgroupPartitionedAdd:
6353 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6354 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6355#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006356 if (isFloat) {
6357 opCode = spv::OpGroupNonUniformFAdd;
6358 } else {
6359 opCode = spv::OpGroupNonUniformIAdd;
6360 }
6361 break;
6362 case glslang::EOpSubgroupMul:
6363 case glslang::EOpSubgroupInclusiveMul:
6364 case glslang::EOpSubgroupExclusiveMul:
6365 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006366#ifdef NV_EXTENSIONS
6367 case glslang::EOpSubgroupPartitionedMul:
6368 case glslang::EOpSubgroupPartitionedInclusiveMul:
6369 case glslang::EOpSubgroupPartitionedExclusiveMul:
6370#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006371 if (isFloat) {
6372 opCode = spv::OpGroupNonUniformFMul;
6373 } else {
6374 opCode = spv::OpGroupNonUniformIMul;
6375 }
6376 break;
6377 case glslang::EOpSubgroupMin:
6378 case glslang::EOpSubgroupInclusiveMin:
6379 case glslang::EOpSubgroupExclusiveMin:
6380 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006381#ifdef NV_EXTENSIONS
6382 case glslang::EOpSubgroupPartitionedMin:
6383 case glslang::EOpSubgroupPartitionedInclusiveMin:
6384 case glslang::EOpSubgroupPartitionedExclusiveMin:
6385#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006386 if (isFloat) {
6387 opCode = spv::OpGroupNonUniformFMin;
6388 } else if (isUnsigned) {
6389 opCode = spv::OpGroupNonUniformUMin;
6390 } else {
6391 opCode = spv::OpGroupNonUniformSMin;
6392 }
6393 break;
6394 case glslang::EOpSubgroupMax:
6395 case glslang::EOpSubgroupInclusiveMax:
6396 case glslang::EOpSubgroupExclusiveMax:
6397 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006398#ifdef NV_EXTENSIONS
6399 case glslang::EOpSubgroupPartitionedMax:
6400 case glslang::EOpSubgroupPartitionedInclusiveMax:
6401 case glslang::EOpSubgroupPartitionedExclusiveMax:
6402#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006403 if (isFloat) {
6404 opCode = spv::OpGroupNonUniformFMax;
6405 } else if (isUnsigned) {
6406 opCode = spv::OpGroupNonUniformUMax;
6407 } else {
6408 opCode = spv::OpGroupNonUniformSMax;
6409 }
6410 break;
6411 case glslang::EOpSubgroupAnd:
6412 case glslang::EOpSubgroupInclusiveAnd:
6413 case glslang::EOpSubgroupExclusiveAnd:
6414 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006415#ifdef NV_EXTENSIONS
6416 case glslang::EOpSubgroupPartitionedAnd:
6417 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6418 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6419#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006420 if (isBool) {
6421 opCode = spv::OpGroupNonUniformLogicalAnd;
6422 } else {
6423 opCode = spv::OpGroupNonUniformBitwiseAnd;
6424 }
6425 break;
6426 case glslang::EOpSubgroupOr:
6427 case glslang::EOpSubgroupInclusiveOr:
6428 case glslang::EOpSubgroupExclusiveOr:
6429 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006430#ifdef NV_EXTENSIONS
6431 case glslang::EOpSubgroupPartitionedOr:
6432 case glslang::EOpSubgroupPartitionedInclusiveOr:
6433 case glslang::EOpSubgroupPartitionedExclusiveOr:
6434#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006435 if (isBool) {
6436 opCode = spv::OpGroupNonUniformLogicalOr;
6437 } else {
6438 opCode = spv::OpGroupNonUniformBitwiseOr;
6439 }
6440 break;
6441 case glslang::EOpSubgroupXor:
6442 case glslang::EOpSubgroupInclusiveXor:
6443 case glslang::EOpSubgroupExclusiveXor:
6444 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006445#ifdef NV_EXTENSIONS
6446 case glslang::EOpSubgroupPartitionedXor:
6447 case glslang::EOpSubgroupPartitionedInclusiveXor:
6448 case glslang::EOpSubgroupPartitionedExclusiveXor:
6449#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006450 if (isBool) {
6451 opCode = spv::OpGroupNonUniformLogicalXor;
6452 } else {
6453 opCode = spv::OpGroupNonUniformBitwiseXor;
6454 }
6455 break;
6456 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6457 case glslang::EOpSubgroupQuadSwapHorizontal:
6458 case glslang::EOpSubgroupQuadSwapVertical:
6459 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6460 default: assert(0 && "Unhandled subgroup operation!");
6461 }
6462
John Kessenich149afc32018-08-14 13:31:43 -06006463 // get the right Group Operation
6464 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006465 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006466 default:
6467 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006468 case glslang::EOpSubgroupBallotBitCount:
6469 case glslang::EOpSubgroupAdd:
6470 case glslang::EOpSubgroupMul:
6471 case glslang::EOpSubgroupMin:
6472 case glslang::EOpSubgroupMax:
6473 case glslang::EOpSubgroupAnd:
6474 case glslang::EOpSubgroupOr:
6475 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006476 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006477 break;
6478 case glslang::EOpSubgroupBallotInclusiveBitCount:
6479 case glslang::EOpSubgroupInclusiveAdd:
6480 case glslang::EOpSubgroupInclusiveMul:
6481 case glslang::EOpSubgroupInclusiveMin:
6482 case glslang::EOpSubgroupInclusiveMax:
6483 case glslang::EOpSubgroupInclusiveAnd:
6484 case glslang::EOpSubgroupInclusiveOr:
6485 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006486 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006487 break;
6488 case glslang::EOpSubgroupBallotExclusiveBitCount:
6489 case glslang::EOpSubgroupExclusiveAdd:
6490 case glslang::EOpSubgroupExclusiveMul:
6491 case glslang::EOpSubgroupExclusiveMin:
6492 case glslang::EOpSubgroupExclusiveMax:
6493 case glslang::EOpSubgroupExclusiveAnd:
6494 case glslang::EOpSubgroupExclusiveOr:
6495 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006496 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006497 break;
6498 case glslang::EOpSubgroupClusteredAdd:
6499 case glslang::EOpSubgroupClusteredMul:
6500 case glslang::EOpSubgroupClusteredMin:
6501 case glslang::EOpSubgroupClusteredMax:
6502 case glslang::EOpSubgroupClusteredAnd:
6503 case glslang::EOpSubgroupClusteredOr:
6504 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006505 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006506 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006507#ifdef NV_EXTENSIONS
6508 case glslang::EOpSubgroupPartitionedAdd:
6509 case glslang::EOpSubgroupPartitionedMul:
6510 case glslang::EOpSubgroupPartitionedMin:
6511 case glslang::EOpSubgroupPartitionedMax:
6512 case glslang::EOpSubgroupPartitionedAnd:
6513 case glslang::EOpSubgroupPartitionedOr:
6514 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006515 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006516 break;
6517 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6518 case glslang::EOpSubgroupPartitionedInclusiveMul:
6519 case glslang::EOpSubgroupPartitionedInclusiveMin:
6520 case glslang::EOpSubgroupPartitionedInclusiveMax:
6521 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6522 case glslang::EOpSubgroupPartitionedInclusiveOr:
6523 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006524 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006525 break;
6526 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6527 case glslang::EOpSubgroupPartitionedExclusiveMul:
6528 case glslang::EOpSubgroupPartitionedExclusiveMin:
6529 case glslang::EOpSubgroupPartitionedExclusiveMax:
6530 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6531 case glslang::EOpSubgroupPartitionedExclusiveOr:
6532 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006533 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006534 break;
6535#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006536 }
6537
John Kessenich149afc32018-08-14 13:31:43 -06006538 // build the instruction
6539 std::vector<spv::IdImmediate> spvGroupOperands;
6540
6541 // Every operation begins with the Execution Scope operand.
6542 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6543 spvGroupOperands.push_back(executionScope);
6544
6545 // Next, for all operations that use a Group Operation, push that as an operand.
6546 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006547 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006548 spvGroupOperands.push_back(groupOperand);
6549 }
6550
John Kessenich66011cb2018-03-06 16:12:04 -07006551 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006552 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6553 spv::IdImmediate operand = { true, *opIt };
6554 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006555 }
6556
6557 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006558 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006559 switch (op) {
6560 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006561 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6562 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6563 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6564 }
6565 if (directionId != spv::NoResult) {
6566 spv::IdImmediate direction = { true, directionId };
6567 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006568 }
6569
6570 return builder.createOp(opCode, typeId, spvGroupOperands);
6571}
6572
John Kessenich5e4b1242015-08-06 22:53:06 -06006573spv::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 -06006574{
John Kessenich66011cb2018-03-06 16:12:04 -07006575 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6576 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006577
John Kessenich140f3df2015-06-26 16:58:36 -06006578 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006579 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006580 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006581 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006582 spv::Id typeId0 = 0;
6583 if (consumedOperands > 0)
6584 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006585 spv::Id typeId1 = 0;
6586 if (consumedOperands > 1)
6587 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006588 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006589
6590 switch (op) {
6591 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006592 if (isFloat)
6593 libCall = spv::GLSLstd450FMin;
6594 else if (isUnsigned)
6595 libCall = spv::GLSLstd450UMin;
6596 else
6597 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006598 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006599 break;
6600 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006601 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006602 break;
6603 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006604 if (isFloat)
6605 libCall = spv::GLSLstd450FMax;
6606 else if (isUnsigned)
6607 libCall = spv::GLSLstd450UMax;
6608 else
6609 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006610 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006611 break;
6612 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006613 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006614 break;
6615 case glslang::EOpDot:
6616 opCode = spv::OpDot;
6617 break;
6618 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006619 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006620 break;
6621
6622 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006623 if (isFloat)
6624 libCall = spv::GLSLstd450FClamp;
6625 else if (isUnsigned)
6626 libCall = spv::GLSLstd450UClamp;
6627 else
6628 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006629 builder.promoteScalar(precision, operands.front(), operands[1]);
6630 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006631 break;
6632 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006633 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6634 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006635 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006636 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006637 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006638 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006639 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006640 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006641 break;
6642 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006643 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006644 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006645 break;
6646 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006647 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006648 builder.promoteScalar(precision, operands[0], operands[2]);
6649 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006650 break;
6651
6652 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006653 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006654 break;
6655 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006656 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006657 break;
6658 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006659 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006660 break;
6661 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006662 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006663 break;
6664 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006665 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006666 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006667 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006668#ifdef AMD_EXTENSIONS
6669 if (typeProxy == glslang::EbtFloat16)
6670 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6671#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006672 libCall = spv::GLSLstd450InterpolateAtSample;
6673 break;
6674 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006675#ifdef AMD_EXTENSIONS
6676 if (typeProxy == glslang::EbtFloat16)
6677 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6678#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006679 libCall = spv::GLSLstd450InterpolateAtOffset;
6680 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006681 case glslang::EOpAddCarry:
6682 opCode = spv::OpIAddCarry;
6683 typeId = builder.makeStructResultType(typeId0, typeId0);
6684 consumedOperands = 2;
6685 break;
6686 case glslang::EOpSubBorrow:
6687 opCode = spv::OpISubBorrow;
6688 typeId = builder.makeStructResultType(typeId0, typeId0);
6689 consumedOperands = 2;
6690 break;
6691 case glslang::EOpUMulExtended:
6692 opCode = spv::OpUMulExtended;
6693 typeId = builder.makeStructResultType(typeId0, typeId0);
6694 consumedOperands = 2;
6695 break;
6696 case glslang::EOpIMulExtended:
6697 opCode = spv::OpSMulExtended;
6698 typeId = builder.makeStructResultType(typeId0, typeId0);
6699 consumedOperands = 2;
6700 break;
6701 case glslang::EOpBitfieldExtract:
6702 if (isUnsigned)
6703 opCode = spv::OpBitFieldUExtract;
6704 else
6705 opCode = spv::OpBitFieldSExtract;
6706 break;
6707 case glslang::EOpBitfieldInsert:
6708 opCode = spv::OpBitFieldInsert;
6709 break;
6710
6711 case glslang::EOpFma:
6712 libCall = spv::GLSLstd450Fma;
6713 break;
6714 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006715 {
6716 libCall = spv::GLSLstd450FrexpStruct;
6717 assert(builder.isPointerType(typeId1));
6718 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006719 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006720#ifdef AMD_EXTENSIONS
6721 if (width == 16)
6722 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6723 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6724#endif
Rex Xu470026f2017-03-29 17:12:40 +08006725 if (builder.getNumComponents(operands[0]) == 1)
6726 frexpIntType = builder.makeIntegerType(width, true);
6727 else
6728 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6729 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6730 consumedOperands = 1;
6731 }
John Kessenich55e7d112015-11-15 21:33:39 -07006732 break;
6733 case glslang::EOpLdexp:
6734 libCall = spv::GLSLstd450Ldexp;
6735 break;
6736
Rex Xu574ab042016-04-14 16:53:07 +08006737 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006738 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006739
John Kessenich66011cb2018-03-06 16:12:04 -07006740 case glslang::EOpSubgroupBroadcast:
6741 case glslang::EOpSubgroupBallotBitExtract:
6742 case glslang::EOpSubgroupShuffle:
6743 case glslang::EOpSubgroupShuffleXor:
6744 case glslang::EOpSubgroupShuffleUp:
6745 case glslang::EOpSubgroupShuffleDown:
6746 case glslang::EOpSubgroupClusteredAdd:
6747 case glslang::EOpSubgroupClusteredMul:
6748 case glslang::EOpSubgroupClusteredMin:
6749 case glslang::EOpSubgroupClusteredMax:
6750 case glslang::EOpSubgroupClusteredAnd:
6751 case glslang::EOpSubgroupClusteredOr:
6752 case glslang::EOpSubgroupClusteredXor:
6753 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006754#ifdef NV_EXTENSIONS
6755 case glslang::EOpSubgroupPartitionedAdd:
6756 case glslang::EOpSubgroupPartitionedMul:
6757 case glslang::EOpSubgroupPartitionedMin:
6758 case glslang::EOpSubgroupPartitionedMax:
6759 case glslang::EOpSubgroupPartitionedAnd:
6760 case glslang::EOpSubgroupPartitionedOr:
6761 case glslang::EOpSubgroupPartitionedXor:
6762 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6763 case glslang::EOpSubgroupPartitionedInclusiveMul:
6764 case glslang::EOpSubgroupPartitionedInclusiveMin:
6765 case glslang::EOpSubgroupPartitionedInclusiveMax:
6766 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6767 case glslang::EOpSubgroupPartitionedInclusiveOr:
6768 case glslang::EOpSubgroupPartitionedInclusiveXor:
6769 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6770 case glslang::EOpSubgroupPartitionedExclusiveMul:
6771 case glslang::EOpSubgroupPartitionedExclusiveMin:
6772 case glslang::EOpSubgroupPartitionedExclusiveMax:
6773 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6774 case glslang::EOpSubgroupPartitionedExclusiveOr:
6775 case glslang::EOpSubgroupPartitionedExclusiveXor:
6776#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006777 return createSubgroupOperation(op, typeId, operands, typeProxy);
6778
Rex Xu9d93a232016-05-05 12:30:44 +08006779#ifdef AMD_EXTENSIONS
6780 case glslang::EOpSwizzleInvocations:
6781 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6782 libCall = spv::SwizzleInvocationsAMD;
6783 break;
6784 case glslang::EOpSwizzleInvocationsMasked:
6785 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6786 libCall = spv::SwizzleInvocationsMaskedAMD;
6787 break;
6788 case glslang::EOpWriteInvocation:
6789 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6790 libCall = spv::WriteInvocationAMD;
6791 break;
6792
6793 case glslang::EOpMin3:
6794 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6795 if (isFloat)
6796 libCall = spv::FMin3AMD;
6797 else {
6798 if (isUnsigned)
6799 libCall = spv::UMin3AMD;
6800 else
6801 libCall = spv::SMin3AMD;
6802 }
6803 break;
6804 case glslang::EOpMax3:
6805 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6806 if (isFloat)
6807 libCall = spv::FMax3AMD;
6808 else {
6809 if (isUnsigned)
6810 libCall = spv::UMax3AMD;
6811 else
6812 libCall = spv::SMax3AMD;
6813 }
6814 break;
6815 case glslang::EOpMid3:
6816 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6817 if (isFloat)
6818 libCall = spv::FMid3AMD;
6819 else {
6820 if (isUnsigned)
6821 libCall = spv::UMid3AMD;
6822 else
6823 libCall = spv::SMid3AMD;
6824 }
6825 break;
6826
6827 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006828 if (typeProxy == glslang::EbtFloat16)
6829 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006830 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6831 libCall = spv::InterpolateAtVertexAMD;
6832 break;
6833#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006834 case glslang::EOpBarrier:
6835 {
6836 // This is for the extended controlBarrier function, with four operands.
6837 // The unextended barrier() goes through createNoArgOperation.
6838 assert(operands.size() == 4);
6839 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6840 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6841 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6842 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6843 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6844 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6845 }
6846 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6847 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6848 }
6849 return 0;
6850 }
6851 break;
6852 case glslang::EOpMemoryBarrier:
6853 {
6854 // This is for the extended memoryBarrier function, with three operands.
6855 // The unextended memoryBarrier() goes through createNoArgOperation.
6856 assert(operands.size() == 3);
6857 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6858 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6859 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6860 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6861 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6862 }
6863 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6864 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6865 }
6866 return 0;
6867 }
6868 break;
Chao Chen3c366992018-09-19 11:41:59 -07006869
6870#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006871 case glslang::EOpReportIntersectionNV:
6872 {
6873 typeId = builder.makeBoolType();
6874 opCode = spv::OpReportIntersectionNVX;
6875 }
6876 break;
6877 case glslang::EOpTraceNV:
6878 {
6879 builder.createNoResultOp(spv::OpTraceNVX, operands);
6880 return 0;
6881 }
6882 break;
Chao Chen3c366992018-09-19 11:41:59 -07006883 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6884 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6885 return 0;
6886#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006887 default:
6888 return 0;
6889 }
6890
6891 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006892 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006893 // Use an extended instruction from the standard library.
6894 // Construct the call arguments, without modifying the original operands vector.
6895 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6896 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006897 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006898 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006899 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006900 case 0:
6901 // should all be handled by visitAggregate and createNoArgOperation
6902 assert(0);
6903 return 0;
6904 case 1:
6905 // should all be handled by createUnaryOperation
6906 assert(0);
6907 return 0;
6908 case 2:
6909 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6910 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006911 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006912 // anything 3 or over doesn't have l-value operands, so all should be consumed
6913 assert(consumedOperands == operands.size());
6914 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006915 break;
6916 }
6917 }
6918
John Kessenich55e7d112015-11-15 21:33:39 -07006919 // Decode the return types that were structures
6920 switch (op) {
6921 case glslang::EOpAddCarry:
6922 case glslang::EOpSubBorrow:
6923 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6924 id = builder.createCompositeExtract(id, typeId0, 0);
6925 break;
6926 case glslang::EOpUMulExtended:
6927 case glslang::EOpIMulExtended:
6928 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6929 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6930 break;
6931 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006932 {
6933 assert(operands.size() == 2);
6934 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6935 // "exp" is floating-point type (from HLSL intrinsic)
6936 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6937 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6938 builder.createStore(member1, operands[1]);
6939 } else
6940 // "exp" is integer type (from GLSL built-in function)
6941 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6942 id = builder.createCompositeExtract(id, typeId0, 0);
6943 }
John Kessenich55e7d112015-11-15 21:33:39 -07006944 break;
6945 default:
6946 break;
6947 }
6948
John Kessenich32cfd492016-02-02 12:37:46 -07006949 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006950}
6951
Rex Xu9d93a232016-05-05 12:30:44 +08006952// Intrinsics with no arguments (or no return value, and no precision).
6953spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006954{
Jeff Bolz36831c92018-09-05 10:11:41 -05006955 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6956 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006957
6958 switch (op) {
6959 case glslang::EOpEmitVertex:
6960 builder.createNoResultOp(spv::OpEmitVertex);
6961 return 0;
6962 case glslang::EOpEndPrimitive:
6963 builder.createNoResultOp(spv::OpEndPrimitive);
6964 return 0;
6965 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006966 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006967 if (glslangIntermediate->usingVulkanMemoryModel()) {
6968 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6969 spv::MemorySemanticsOutputMemoryKHRMask |
6970 spv::MemorySemanticsAcquireReleaseMask);
6971 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6972 } else {
6973 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6974 }
John Kessenich82979362017-12-11 04:02:24 -07006975 } else {
6976 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6977 spv::MemorySemanticsWorkgroupMemoryMask |
6978 spv::MemorySemanticsAcquireReleaseMask);
6979 }
John Kessenich140f3df2015-06-26 16:58:36 -06006980 return 0;
6981 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006982 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6983 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006984 return 0;
6985 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006986 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6987 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006988 return 0;
6989 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006990 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6991 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006992 return 0;
6993 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006994 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6995 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006996 return 0;
6997 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006998 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6999 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007000 return 0;
7001 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007002 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7003 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007004 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007005 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007006 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007007 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007008 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007009 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007010 case glslang::EOpDeviceMemoryBarrier:
7011 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7012 spv::MemorySemanticsImageMemoryMask |
7013 spv::MemorySemanticsAcquireReleaseMask);
7014 return 0;
7015 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7016 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7017 spv::MemorySemanticsImageMemoryMask |
7018 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007019 return 0;
7020 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007021 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7022 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007023 return 0;
7024 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007025 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7026 spv::MemorySemanticsWorkgroupMemoryMask |
7027 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007028 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007029 case glslang::EOpSubgroupBarrier:
7030 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7031 spv::MemorySemanticsAcquireReleaseMask);
7032 return spv::NoResult;
7033 case glslang::EOpSubgroupMemoryBarrier:
7034 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7035 spv::MemorySemanticsAcquireReleaseMask);
7036 return spv::NoResult;
7037 case glslang::EOpSubgroupMemoryBarrierBuffer:
7038 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7039 spv::MemorySemanticsAcquireReleaseMask);
7040 return spv::NoResult;
7041 case glslang::EOpSubgroupMemoryBarrierImage:
7042 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7043 spv::MemorySemanticsAcquireReleaseMask);
7044 return spv::NoResult;
7045 case glslang::EOpSubgroupMemoryBarrierShared:
7046 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7047 spv::MemorySemanticsAcquireReleaseMask);
7048 return spv::NoResult;
7049 case glslang::EOpSubgroupElect: {
7050 std::vector<spv::Id> operands;
7051 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7052 }
Rex Xu9d93a232016-05-05 12:30:44 +08007053#ifdef AMD_EXTENSIONS
7054 case glslang::EOpTime:
7055 {
7056 std::vector<spv::Id> args; // Dummy arguments
7057 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7058 return builder.setPrecision(id, precision);
7059 }
7060#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007061#ifdef NV_EXTENSIONS
7062 case glslang::EOpIgnoreIntersectionNV:
7063 builder.createNoResultOp(spv::OpIgnoreIntersectionNVX);
7064 return 0;
7065 case glslang::EOpTerminateRayNV:
7066 builder.createNoResultOp(spv::OpTerminateRayNVX);
7067 return 0;
7068#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007069 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007070 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007071 return 0;
7072 }
7073}
7074
7075spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7076{
John Kessenich2f273362015-07-18 22:34:27 -06007077 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007078 spv::Id id;
7079 if (symbolValues.end() != iter) {
7080 id = iter->second;
7081 return id;
7082 }
7083
7084 // it was not found, create it
7085 id = createSpvVariable(symbol);
7086 symbolValues[symbol->getId()] = id;
7087
Rex Xuc884b4a2016-06-29 15:03:44 +08007088 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007089 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7090 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7091 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007092#ifdef NV_EXTENSIONS
7093 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7094#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007095 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007096 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007097 if (symbol->getQualifier().hasIndex())
7098 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7099 if (symbol->getQualifier().hasComponent())
7100 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007101 // atomic counters use this:
7102 if (symbol->getQualifier().hasOffset())
7103 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007104 }
7105
scygan2c864272016-05-18 18:09:17 +02007106 if (symbol->getQualifier().hasLocation())
7107 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007108 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007109 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007110 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007111 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007112 }
John Kessenich140f3df2015-06-26 16:58:36 -06007113 if (symbol->getQualifier().hasSet())
7114 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007115 else if (IsDescriptorResource(symbol->getType())) {
7116 // default to 0
7117 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7118 }
John Kessenich140f3df2015-06-26 16:58:36 -06007119 if (symbol->getQualifier().hasBinding())
7120 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007121 if (symbol->getQualifier().hasAttachment())
7122 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007123 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007124 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007125 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007126 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007127 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007128 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007129 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7130 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7131 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7132 }
7133 if (symbol->getQualifier().hasXfbOffset())
7134 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007135 }
7136
Rex Xu1da878f2016-02-21 20:59:01 +08007137 if (symbol->getType().isImage()) {
7138 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007139 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007140 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007141 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007142 }
7143
John Kessenich140f3df2015-06-26 16:58:36 -06007144 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007145 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007146 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007147 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007148
John Kessenich5611c6d2018-04-05 11:25:02 -06007149 // nonuniform
7150 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7151
John Kessenichecba76f2017-01-06 00:34:48 -07007152#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007153 if (builtIn == spv::BuiltInSampleMask) {
7154 spv::Decoration decoration;
7155 // GL_NV_sample_mask_override_coverage extension
7156 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007157 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007158 else
7159 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007160 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007161 if (decoration != spv::DecorationMax) {
7162 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7163 }
7164 }
chaoc771d89f2017-01-13 01:10:53 -08007165 else if (builtIn == spv::BuiltInLayer) {
7166 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007167 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007168 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007169 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7170 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7171 }
John Kessenichb41bff62017-08-11 13:07:17 -06007172 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007173 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7174 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007175 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7176 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7177 }
7178 }
7179
chaoc6e5acae2016-12-20 13:28:52 -08007180 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007181 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007182 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007183 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7184 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007185 if (symbol->getQualifier().pervertexNV) {
7186 builder.addDecoration(id, spv::DecorationPerVertexNV);
7187 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7188 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7189 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007190#endif
7191
John Kessenich5d610ee2018-03-07 18:05:55 -07007192 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7193 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7194 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7195 symbol->getType().getQualifier().semanticName);
7196 }
7197
John Kessenich140f3df2015-06-26 16:58:36 -06007198 return id;
7199}
7200
Chao Chen3c366992018-09-19 11:41:59 -07007201#ifdef NV_EXTENSIONS
7202// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7203void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7204{
7205 if (member >= 0) {
7206 if (qualifier.perPrimitiveNV)
7207 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
7208 if (qualifier.perViewNV)
7209 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7210 if (qualifier.perTaskNV)
7211 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7212 } else {
7213 if (qualifier.perPrimitiveNV)
7214 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
7215 if (qualifier.perViewNV)
7216 builder.addDecoration(id, spv::DecorationPerViewNV);
7217 if (qualifier.perTaskNV)
7218 builder.addDecoration(id, spv::DecorationPerTaskNV);
7219 }
7220}
7221#endif
7222
John Kessenich55e7d112015-11-15 21:33:39 -07007223// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007224// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007225//
7226// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7227//
7228// Recursively walk the nodes. The nodes form a tree whose leaves are
7229// regular constants, which themselves are trees that createSpvConstant()
7230// recursively walks. So, this function walks the "top" of the tree:
7231// - emit specialization constant-building instructions for specConstant
7232// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007233spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007234{
John Kessenich7cc0e282016-03-20 00:46:02 -06007235 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007236
qining4f4bb812016-04-03 23:55:17 -04007237 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007238 if (! node.getQualifier().specConstant) {
7239 // hand off to the non-spec-constant path
7240 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7241 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007242 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007243 nextConst, false);
7244 }
7245
7246 // We now know we have a specialization constant to build
7247
John Kessenichd94c0032016-05-30 19:29:40 -06007248 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007249 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7250 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7251 std::vector<spv::Id> dimConstId;
7252 for (int dim = 0; dim < 3; ++dim) {
7253 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7254 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007255 if (specConst) {
7256 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7257 glslangIntermediate->getLocalSizeSpecId(dim));
7258 }
qining4f4bb812016-04-03 23:55:17 -04007259 }
7260 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7261 }
7262
7263 // An AST node labelled as specialization constant should be a symbol node.
7264 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7265 if (auto* sn = node.getAsSymbolNode()) {
7266 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007267 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7268 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7269 // will set the builder into spec constant op instruction generating mode.
7270 sub_tree->traverse(this);
7271 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04007272 } else if (auto* const_union_array = &sn->getConstArray()){
7273 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01007274 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
7275 builder.addName(id, sn->getName().c_str());
7276 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07007277 }
7278 }
qining4f4bb812016-04-03 23:55:17 -04007279
7280 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7281 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007282 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007283 exit(1);
7284 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007285}
7286
John Kessenich140f3df2015-06-26 16:58:36 -06007287// Use 'consts' as the flattened glslang source of scalar constants to recursively
7288// build the aggregate SPIR-V constant.
7289//
7290// If there are not enough elements present in 'consts', 0 will be substituted;
7291// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7292//
qining08408382016-03-21 09:51:37 -04007293spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007294{
7295 // vector of constants for SPIR-V
7296 std::vector<spv::Id> spvConsts;
7297
7298 // Type is used for struct and array constants
7299 spv::Id typeId = convertGlslangToSpvType(glslangType);
7300
7301 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007302 glslang::TType elementType(glslangType, 0);
7303 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007304 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007305 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007306 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007307 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007308 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007309 } else if (glslangType.getStruct()) {
7310 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7311 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007312 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007313 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007314 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7315 bool zero = nextConst >= consts.size();
7316 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007317 case glslang::EbtInt8:
7318 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7319 break;
7320 case glslang::EbtUint8:
7321 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7322 break;
7323 case glslang::EbtInt16:
7324 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7325 break;
7326 case glslang::EbtUint16:
7327 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7328 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007329 case glslang::EbtInt:
7330 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7331 break;
7332 case glslang::EbtUint:
7333 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7334 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007335 case glslang::EbtInt64:
7336 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7337 break;
7338 case glslang::EbtUint64:
7339 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7340 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007341 case glslang::EbtFloat:
7342 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7343 break;
7344 case glslang::EbtDouble:
7345 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7346 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007347 case glslang::EbtFloat16:
7348 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7349 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007350 case glslang::EbtBool:
7351 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7352 break;
7353 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007354 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007355 break;
7356 }
7357 ++nextConst;
7358 }
7359 } else {
7360 // we have a non-aggregate (scalar) constant
7361 bool zero = nextConst >= consts.size();
7362 spv::Id scalar = 0;
7363 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007364 case glslang::EbtInt8:
7365 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7366 break;
7367 case glslang::EbtUint8:
7368 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7369 break;
7370 case glslang::EbtInt16:
7371 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7372 break;
7373 case glslang::EbtUint16:
7374 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007376 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007377 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007378 break;
7379 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007380 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007381 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007382 case glslang::EbtInt64:
7383 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7384 break;
7385 case glslang::EbtUint64:
7386 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7387 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007388 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007389 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007390 break;
7391 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007392 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007393 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007394 case glslang::EbtFloat16:
7395 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7396 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007397 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007398 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007399 break;
7400 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007401 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007402 break;
7403 }
7404 ++nextConst;
7405 return scalar;
7406 }
7407
7408 return builder.makeCompositeConstant(typeId, spvConsts);
7409}
7410
John Kessenich7c1aa102015-10-15 13:29:11 -06007411// Return true if the node is a constant or symbol whose reading has no
7412// non-trivial observable cost or effect.
7413bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7414{
7415 // don't know what this is
7416 if (node == nullptr)
7417 return false;
7418
7419 // a constant is safe
7420 if (node->getAsConstantUnion() != nullptr)
7421 return true;
7422
7423 // not a symbol means non-trivial
7424 if (node->getAsSymbolNode() == nullptr)
7425 return false;
7426
7427 // a symbol, depends on what's being read
7428 switch (node->getType().getQualifier().storage) {
7429 case glslang::EvqTemporary:
7430 case glslang::EvqGlobal:
7431 case glslang::EvqIn:
7432 case glslang::EvqInOut:
7433 case glslang::EvqConst:
7434 case glslang::EvqConstReadOnly:
7435 case glslang::EvqUniform:
7436 return true;
7437 default:
7438 return false;
7439 }
qining25262b32016-05-06 17:25:16 -04007440}
John Kessenich7c1aa102015-10-15 13:29:11 -06007441
7442// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007443// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007444// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007445// Return true if trivial.
7446bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7447{
7448 if (node == nullptr)
7449 return false;
7450
John Kessenich84cc15f2017-05-24 16:44:47 -06007451 // count non scalars as trivial, as well as anything coming from HLSL
7452 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007453 return true;
7454
John Kessenich7c1aa102015-10-15 13:29:11 -06007455 // symbols and constants are trivial
7456 if (isTrivialLeaf(node))
7457 return true;
7458
7459 // otherwise, it needs to be a simple operation or one or two leaf nodes
7460
7461 // not a simple operation
7462 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7463 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7464 if (binaryNode == nullptr && unaryNode == nullptr)
7465 return false;
7466
7467 // not on leaf nodes
7468 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7469 return false;
7470
7471 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7472 return false;
7473 }
7474
7475 switch (node->getAsOperator()->getOp()) {
7476 case glslang::EOpLogicalNot:
7477 case glslang::EOpConvIntToBool:
7478 case glslang::EOpConvUintToBool:
7479 case glslang::EOpConvFloatToBool:
7480 case glslang::EOpConvDoubleToBool:
7481 case glslang::EOpEqual:
7482 case glslang::EOpNotEqual:
7483 case glslang::EOpLessThan:
7484 case glslang::EOpGreaterThan:
7485 case glslang::EOpLessThanEqual:
7486 case glslang::EOpGreaterThanEqual:
7487 case glslang::EOpIndexDirect:
7488 case glslang::EOpIndexDirectStruct:
7489 case glslang::EOpLogicalXor:
7490 case glslang::EOpAny:
7491 case glslang::EOpAll:
7492 return true;
7493 default:
7494 return false;
7495 }
7496}
7497
7498// Emit short-circuiting code, where 'right' is never evaluated unless
7499// the left side is true (for &&) or false (for ||).
7500spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7501{
7502 spv::Id boolTypeId = builder.makeBoolType();
7503
7504 // emit left operand
7505 builder.clearAccessChain();
7506 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007507 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007508
7509 // Operands to accumulate OpPhi operands
7510 std::vector<spv::Id> phiOperands;
7511 // accumulate left operand's phi information
7512 phiOperands.push_back(leftId);
7513 phiOperands.push_back(builder.getBuildPoint()->getId());
7514
7515 // Make the two kinds of operation symmetric with a "!"
7516 // || => emit "if (! left) result = right"
7517 // && => emit "if ( left) result = right"
7518 //
7519 // TODO: this runtime "not" for || could be avoided by adding functionality
7520 // to 'builder' to have an "else" without an "then"
7521 if (op == glslang::EOpLogicalOr)
7522 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7523
7524 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007525 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007526
7527 // emit right operand as the "then" part of the "if"
7528 builder.clearAccessChain();
7529 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007530 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007531
7532 // accumulate left operand's phi information
7533 phiOperands.push_back(rightId);
7534 phiOperands.push_back(builder.getBuildPoint()->getId());
7535
7536 // finish the "if"
7537 ifBuilder.makeEndIf();
7538
7539 // phi together the two results
7540 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7541}
7542
Frank Henigman541f7bb2018-01-16 00:18:26 -05007543#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007544// Return type Id of the imported set of extended instructions corresponds to the name.
7545// Import this set if it has not been imported yet.
7546spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7547{
7548 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7549 return extBuiltinMap[name];
7550 else {
Rex Xu51596642016-09-21 18:56:12 +08007551 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007552 spv::Id extBuiltins = builder.import(name);
7553 extBuiltinMap[name] = extBuiltins;
7554 return extBuiltins;
7555 }
7556}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007557#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007558
John Kessenich140f3df2015-06-26 16:58:36 -06007559}; // end anonymous namespace
7560
7561namespace glslang {
7562
John Kessenich68d78fd2015-07-12 19:28:10 -06007563void GetSpirvVersion(std::string& version)
7564{
John Kessenich9e55f632015-07-15 10:03:39 -06007565 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007566 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007567 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007568 version = buf;
7569}
7570
John Kessenicha372a3e2017-11-02 22:32:14 -06007571// For low-order part of the generator's magic number. Bump up
7572// when there is a change in the style (e.g., if SSA form changes,
7573// or a different instruction sequence to do something gets used).
7574int GetSpirvGeneratorVersion()
7575{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007576 // return 1; // start
7577 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007578 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007579 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007580 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007581 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7582 // versions 4 and 6 each generate OpArrayLength as it has long been done
7583 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007584}
7585
John Kessenich140f3df2015-06-26 16:58:36 -06007586// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007587void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007588{
7589 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007590 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007591 if (out.fail())
7592 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007593 for (int i = 0; i < (int)spirv.size(); ++i) {
7594 unsigned int word = spirv[i];
7595 out.write((const char*)&word, 4);
7596 }
7597 out.close();
7598}
7599
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007600// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007601void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007602{
7603 std::ofstream out;
7604 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007605 if (out.fail())
7606 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007607 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007608 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007609 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007610 if (varName != nullptr) {
7611 out << "\t #pragma once" << std::endl;
7612 out << "const uint32_t " << varName << "[] = {" << std::endl;
7613 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007614 const int WORDS_PER_LINE = 8;
7615 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7616 out << "\t";
7617 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7618 const unsigned int word = spirv[i + j];
7619 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7620 if (i + j + 1 < (int)spirv.size()) {
7621 out << ",";
7622 }
7623 }
7624 out << std::endl;
7625 }
Flavio15017db2017-02-15 14:29:33 -08007626 if (varName != nullptr) {
7627 out << "};";
7628 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007629 out.close();
7630}
7631
John Kessenich140f3df2015-06-26 16:58:36 -06007632//
7633// Set up the glslang traversal
7634//
John Kessenich4e11b612018-08-30 16:56:59 -06007635void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007636{
Lei Zhang17535f72016-05-04 15:55:59 -04007637 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007638 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007639}
7640
John Kessenich4e11b612018-08-30 16:56:59 -06007641void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007642 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007643{
John Kessenich140f3df2015-06-26 16:58:36 -06007644 TIntermNode* root = intermediate.getTreeRoot();
7645
7646 if (root == 0)
7647 return;
7648
John Kessenich4e11b612018-08-30 16:56:59 -06007649 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007650 if (options == nullptr)
7651 options = &defaultOptions;
7652
John Kessenich4e11b612018-08-30 16:56:59 -06007653 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007654
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007655 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007656 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007657 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007658 it.dumpSpv(spirv);
7659
GregFfb03a552018-03-29 11:49:14 -06007660#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007661 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7662 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007663 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007664 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007665
John Kessenich4e11b612018-08-30 16:56:59 -06007666 if (options->validate)
7667 SpirvToolsValidate(intermediate, spirv, logger);
7668
John Kessenich717c80a2018-08-23 15:17:10 -06007669 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007670 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007671
GregFcd1f1692017-09-21 18:40:22 -06007672#endif
7673
John Kessenich4e11b612018-08-30 16:56:59 -06007674 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007675}
7676
7677}; // end namespace glslang