blob: 3d0f0c7ac0c08744f6e926e824a7e1ba267af006 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 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 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 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 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 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 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
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::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
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::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
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::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
891 // raytracing
892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700928 case glslang::EbvTaskCountNV:
929 return spv::BuiltInTaskCountNV;
930 case glslang::EbvPrimitiveCountNV:
931 return spv::BuiltInPrimitiveCountNV;
932 case glslang::EbvPrimitiveIndicesNV:
933 return spv::BuiltInPrimitiveIndicesNV;
934 case glslang::EbvClipDistancePerViewNV:
935 return spv::BuiltInClipDistancePerViewNV;
936 case glslang::EbvCullDistancePerViewNV:
937 return spv::BuiltInCullDistancePerViewNV;
938 case glslang::EbvLayerPerViewNV:
939 return spv::BuiltInLayerPerViewNV;
940 case glslang::EbvMeshViewCountNV:
941 return spv::BuiltInMeshViewCountNV;
942 case glslang::EbvMeshViewIndicesNV:
943 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800944#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800945 default:
946 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948}
949
Rex Xufc618912015-09-09 16:42:49 +0800950// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700951spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800952{
953 assert(type.getBasicType() == glslang::EbtSampler);
954
John Kessenich5d0fa972016-02-15 11:57:00 -0700955 // Check for capabilities
956 switch (type.getQualifier().layoutFormat) {
957 case glslang::ElfRg32f:
958 case glslang::ElfRg16f:
959 case glslang::ElfR11fG11fB10f:
960 case glslang::ElfR16f:
961 case glslang::ElfRgba16:
962 case glslang::ElfRgb10A2:
963 case glslang::ElfRg16:
964 case glslang::ElfRg8:
965 case glslang::ElfR16:
966 case glslang::ElfR8:
967 case glslang::ElfRgba16Snorm:
968 case glslang::ElfRg16Snorm:
969 case glslang::ElfRg8Snorm:
970 case glslang::ElfR16Snorm:
971 case glslang::ElfR8Snorm:
972
973 case glslang::ElfRg32i:
974 case glslang::ElfRg16i:
975 case glslang::ElfRg8i:
976 case glslang::ElfR16i:
977 case glslang::ElfR8i:
978
979 case glslang::ElfRgb10a2ui:
980 case glslang::ElfRg32ui:
981 case glslang::ElfRg16ui:
982 case glslang::ElfRg8ui:
983 case glslang::ElfR16ui:
984 case glslang::ElfR8ui:
985 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
986 break;
987
988 default:
989 break;
990 }
991
992 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800993 switch (type.getQualifier().layoutFormat) {
994 case glslang::ElfNone: return spv::ImageFormatUnknown;
995 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
996 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
997 case glslang::ElfR32f: return spv::ImageFormatR32f;
998 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
999 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1000 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1001 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1002 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1003 case glslang::ElfR16f: return spv::ImageFormatR16f;
1004 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1005 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1006 case glslang::ElfRg16: return spv::ImageFormatRg16;
1007 case glslang::ElfRg8: return spv::ImageFormatRg8;
1008 case glslang::ElfR16: return spv::ImageFormatR16;
1009 case glslang::ElfR8: return spv::ImageFormatR8;
1010 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1011 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1012 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1013 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1014 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1015 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1016 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1017 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1018 case glslang::ElfR32i: return spv::ImageFormatR32i;
1019 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1020 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1021 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1022 case glslang::ElfR16i: return spv::ImageFormatR16i;
1023 case glslang::ElfR8i: return spv::ImageFormatR8i;
1024 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1025 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1026 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1027 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1028 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1029 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1030 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1031 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1032 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1033 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001035 }
1036}
1037
John Kesseniche18fd202018-01-30 11:01:39 -07001038spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001039{
John Kesseniche18fd202018-01-30 11:01:39 -07001040 if (selectionNode.getFlatten())
1041 return spv::SelectionControlFlattenMask;
1042 if (selectionNode.getDontFlatten())
1043 return spv::SelectionControlDontFlattenMask;
1044 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (switchNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (switchNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
1054}
1055
John Kessenicha2858d92018-01-31 08:11:18 -07001056// return a non-0 dependency if the dependency argument must be set
1057spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001058 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001059{
1060 spv::LoopControlMask control = spv::LoopControlMaskNone;
1061
1062 if (loopNode.getDontUnroll())
1063 control = control | spv::LoopControlDontUnrollMask;
1064 if (loopNode.getUnroll())
1065 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001066 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001067 control = control | spv::LoopControlDependencyInfiniteMask;
1068 else if (loopNode.getLoopDependency() > 0) {
1069 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001070 operands.push_back((unsigned int)loopNode.getLoopDependency());
1071 }
1072 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1073 if (loopNode.getMinIterations() > 0) {
1074 control = control | spv::LoopControlMinIterationsMask;
1075 operands.push_back(loopNode.getMinIterations());
1076 }
1077 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1078 control = control | spv::LoopControlMaxIterationsMask;
1079 operands.push_back(loopNode.getMaxIterations());
1080 }
1081 if (loopNode.getIterationMultiple() > 1) {
1082 control = control | spv::LoopControlIterationMultipleMask;
1083 operands.push_back(loopNode.getIterationMultiple());
1084 }
1085 if (loopNode.getPeelCount() > 0) {
1086 control = control | spv::LoopControlPeelCountMask;
1087 operands.push_back(loopNode.getPeelCount());
1088 }
1089 if (loopNode.getPartialCount() > 0) {
1090 control = control | spv::LoopControlPartialCountMask;
1091 operands.push_back(loopNode.getPartialCount());
1092 }
John Kessenicha2858d92018-01-31 08:11:18 -07001093 }
John Kesseniche18fd202018-01-30 11:01:39 -07001094
1095 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001096}
1097
John Kessenicha5c5fb62017-05-05 05:09:58 -06001098// Translate glslang type to SPIR-V storage class.
1099spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1100{
1101 if (type.getQualifier().isPipeInput())
1102 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001103 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001104 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001105
1106 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1107 type.getQualifier().storage == glslang::EvqUniform) {
1108 if (type.getBasicType() == glslang::EbtAtomicUint)
1109 return spv::StorageClassAtomicCounter;
1110 if (type.containsOpaque())
1111 return spv::StorageClassUniformConstant;
1112 }
1113
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001114#ifdef NV_EXTENSIONS
1115 if (type.getQualifier().isUniformOrBuffer() &&
1116 type.getQualifier().layoutShaderRecordNV) {
1117 return spv::StorageClassShaderRecordBufferNV;
1118 }
1119#endif
1120
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001122 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001123 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 }
1125
1126 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 if (type.getQualifier().layoutPushConstant)
1128 return spv::StorageClassPushConstant;
1129 if (type.getBasicType() == glslang::EbtBlock)
1130 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001131 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001132 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133
1134 switch (type.getQualifier().storage) {
1135 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1136 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1137 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1138 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001139#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001140 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1141 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1142 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1143 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1144 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001145#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 default:
1147 assert(0);
1148 break;
1149 }
1150
1151 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152}
1153
John Kessenich5611c6d2018-04-05 11:25:02 -06001154// Add capabilities pertaining to how an array is indexed.
1155void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1156 const glslang::TType& indexType)
1157{
1158 if (indexType.getQualifier().isNonUniform()) {
1159 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001160 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 if (baseType.getBasicType() == glslang::EbtSampler) {
1162 if (baseType.getQualifier().hasAttachment())
1163 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1164 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1165 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1166 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage())
1169 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture())
1171 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1172 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1173 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1174 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1175 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1176 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1177 }
1178 } else {
1179 // assume a dynamically uniform index
1180 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001181 if (baseType.getQualifier().hasAttachment()) {
1182 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001184 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1185 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001187 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1188 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 }
1192 }
1193}
1194
qining25262b32016-05-06 17:25:16 -04001195// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001196// descriptor set.
1197bool IsDescriptorResource(const glslang::TType& type)
1198{
John Kessenichf7497e22016-03-08 21:36:22 -07001199 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001200 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001201 return type.getQualifier().isUniformOrBuffer() &&
1202#ifdef NV_EXTENSIONS
1203 ! type.getQualifier().layoutShaderRecordNV &&
1204#endif
1205 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001206
1207 // non block...
1208 // basically samplerXXX/subpass/sampler/texture are all included
1209 // if they are the global-scope-class, not the function parameter
1210 // (or local, if they ever exist) class.
1211 if (type.getBasicType() == glslang::EbtSampler)
1212 return type.getQualifier().isUniformOrBuffer();
1213
1214 // None of the above.
1215 return false;
1216}
1217
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1219{
1220 if (child.layoutMatrix == glslang::ElmNone)
1221 child.layoutMatrix = parent.layoutMatrix;
1222
1223 if (parent.invariant)
1224 child.invariant = true;
1225 if (parent.nopersp)
1226 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001227#ifdef AMD_EXTENSIONS
1228 if (parent.explicitInterp)
1229 child.explicitInterp = true;
1230#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001231 if (parent.flat)
1232 child.flat = true;
1233 if (parent.centroid)
1234 child.centroid = true;
1235 if (parent.patch)
1236 child.patch = true;
1237 if (parent.sample)
1238 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.coherent)
1240 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001241 if (parent.devicecoherent)
1242 child.devicecoherent = true;
1243 if (parent.queuefamilycoherent)
1244 child.queuefamilycoherent = true;
1245 if (parent.workgroupcoherent)
1246 child.workgroupcoherent = true;
1247 if (parent.subgroupcoherent)
1248 child.subgroupcoherent = true;
1249 if (parent.nonprivate)
1250 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001251 if (parent.volatil)
1252 child.volatil = true;
1253 if (parent.restrict)
1254 child.restrict = true;
1255 if (parent.readonly)
1256 child.readonly = true;
1257 if (parent.writeonly)
1258 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001259#ifdef NV_EXTENSIONS
1260 if (parent.perPrimitiveNV)
1261 child.perPrimitiveNV = true;
1262 if (parent.perViewNV)
1263 child.perViewNV = true;
1264 if (parent.perTaskNV)
1265 child.perTaskNV = true;
1266#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001267}
1268
John Kessenichf2b7f332016-09-01 17:05:23 -06001269bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001270{
John Kessenich7b9fa252016-01-21 18:56:57 -07001271 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001272 // - struct members might inherit from a struct declaration
1273 // (note that non-block structs don't explicitly inherit,
1274 // only implicitly, meaning no decoration involved)
1275 // - affect decorations on the struct members
1276 // (note smooth does not, and expecting something like volatile
1277 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001278 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001279 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001280}
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282//
1283// Implement the TGlslangToSpvTraverser class.
1284//
1285
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001286TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001287 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1288 : TIntermTraverser(true, false, true),
1289 options(options),
1290 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001291 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001292 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001293 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001294 glslangIntermediate(glslangIntermediate)
1295{
1296 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1297
1298 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001299 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1300 glslangIntermediate->getVersion());
1301
John Kessenich121853f2017-05-31 17:11:16 -06001302 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001303 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001304 builder.setSourceFile(glslangIntermediate->getSourceFile());
1305
1306 // Set the source shader's text. If for SPV version 1.0, include
1307 // a preamble in comments stating the OpModuleProcessed instructions.
1308 // Otherwise, emit those as actual instructions.
1309 std::string text;
1310 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1311 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001312 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001313 text.append("// OpModuleProcessed ");
1314 text.append(processes[p]);
1315 text.append("\n");
1316 } else
1317 builder.addModuleProcessed(processes[p]);
1318 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001319 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001320 text.append("#line 1\n");
1321 text.append(glslangIntermediate->getSourceText());
1322 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001323 // Pass name and text for all included files
1324 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1325 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1326 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001327 }
John Kessenich140f3df2015-06-26 16:58:36 -06001328 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001329
1330 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1331 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1332
1333 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1334 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1335 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1336 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1337 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001338 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001339 memoryModel = spv::MemoryModelVulkanKHR;
1340 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 builder.setMemoryModel(addressingModel, memoryModel);
1344
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001345 if (glslangIntermediate->usingVariablePointers()) {
1346 builder.addCapability(spv::CapabilityVariablePointers);
1347 }
1348
John Kessenicheee9d532016-09-19 18:09:30 -06001349 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1350 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001353 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1354 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001355 builder.addSourceExtension(it->c_str());
1356
1357 // Add the top-level modes for this shader.
1358
John Kessenich92187592016-02-01 13:45:25 -07001359 if (glslangIntermediate->getXfbMode()) {
1360 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001362 }
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 unsigned int mode;
1365 switch (glslangIntermediate->getStage()) {
1366 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001367 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001368 break;
1369
steve-lunarge7412492017-03-23 11:56:07 -06001370 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001371 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001372 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
steve-lunarge7412492017-03-23 11:56:07 -06001374 glslang::TLayoutGeometry primitive;
1375
1376 if (glslangIntermediate->getStage() == EShLangTessControl) {
1377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1378 primitive = glslangIntermediate->getOutputPrimitive();
1379 } else {
1380 primitive = glslangIntermediate->getInputPrimitive();
1381 }
1382
1383 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001384 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1385 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1386 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001387 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 }
John Kessenich4016e382016-07-15 11:53:56 -06001389 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001390 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1391
John Kesseniche6903322015-10-13 16:29:02 -06001392 switch (glslangIntermediate->getVertexSpacing()) {
1393 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1394 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1395 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001396 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001397 }
John Kessenich4016e382016-07-15 11:53:56 -06001398 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1400
1401 switch (glslangIntermediate->getVertexOrder()) {
1402 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1403 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001404 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001405 }
John Kessenich4016e382016-07-15 11:53:56 -06001406 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001407 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1408
1409 if (glslangIntermediate->getPointMode())
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001411 break;
1412
1413 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 switch (glslangIntermediate->getInputPrimitive()) {
1416 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1417 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1418 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001419 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001421 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001422 }
John Kessenich4016e382016-07-15 11:53:56 -06001423 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001425
John Kessenich140f3df2015-06-26 16:58:36 -06001426 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1427
1428 switch (glslangIntermediate->getOutputPrimitive()) {
1429 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1430 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1431 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001432 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001433 }
John Kessenich4016e382016-07-15 11:53:56 -06001434 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001435 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1437 break;
1438
1439 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001440 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 if (glslangIntermediate->getPixelCenterInteger())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001443
John Kessenich140f3df2015-06-26 16:58:36 -06001444 if (glslangIntermediate->getOriginUpperLeft())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 else
1447 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001448
1449 if (glslangIntermediate->getEarlyFragmentTests())
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1451
chaocc1204522017-06-30 17:14:30 -07001452 if (glslangIntermediate->getPostDepthCoverage()) {
1453 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1455 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1456 }
1457
John Kesseniche6903322015-10-13 16:29:02 -06001458 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001459 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1460 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001461 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001462 }
John Kessenich4016e382016-07-15 11:53:56 -06001463 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001464 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1465
1466 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001468 break;
1469
1470 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1473 glslangIntermediate->getLocalSize(1),
1474 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001475#ifdef NV_EXTENSIONS
1476 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1477 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1479 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1480 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1481 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1483 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1484 }
1485#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001486 break;
1487
Chao Chen3c366992018-09-19 11:41:59 -07001488#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001489 case EShLangRayGenNV:
1490 case EShLangIntersectNV:
1491 case EShLangAnyHitNV:
1492 case EShLangClosestHitNV:
1493 case EShLangMissNV:
1494 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001495 builder.addCapability(spv::CapabilityRayTracingNV);
1496 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001497 break;
Chao Chen3c366992018-09-19 11:41:59 -07001498 case EShLangTaskNV:
1499 case EShLangMeshNV:
1500 builder.addCapability(spv::CapabilityMeshShadingNV);
1501 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1508
1509 switch (glslangIntermediate->getOutputPrimitive()) {
1510 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1511 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1512 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1513 default: mode = spv::ExecutionModeMax; break;
1514 }
1515 if (mode != spv::ExecutionModeMax)
1516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1517 }
1518 break;
1519#endif
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521 default:
1522 break;
1523 }
John Kessenich140f3df2015-06-26 16:58:36 -06001524}
1525
John Kessenichfca82622016-11-26 13:23:20 -07001526// Finish creating SPV, after the traversal is complete.
1527void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001528{
John Kessenichf04c51b2018-08-03 15:56:12 -06001529 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001531 builder.setBuildPoint(shaderEntry->getLastBlock());
1532 builder.leaveFunction();
1533 }
1534
John Kessenich7ba63412015-12-20 17:37:07 -07001535 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001536 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1537 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001538
John Kessenichf04c51b2018-08-03 15:56:12 -06001539 // Add capabilities, extensions, remove unneeded decorations, etc.,
1540 // based on the resulting SPIR-V.
1541 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001542}
1543
John Kessenichfca82622016-11-26 13:23:20 -07001544// Write the SPV into 'out'.
1545void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001546{
John Kessenichfca82622016-11-26 13:23:20 -07001547 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001548}
1549
1550//
1551// Implement the traversal functions.
1552//
1553// Return true from interior nodes to have the external traversal
1554// continue on to children. Return false if children were
1555// already processed.
1556//
1557
1558//
qining25262b32016-05-06 17:25:16 -04001559// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001560// - uniform/input reads
1561// - output writes
1562// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1563// - something simple that degenerates into the last bullet
1564//
1565void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1566{
qining75d1d802016-04-06 14:42:01 -04001567 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1568 if (symbol->getType().getQualifier().isSpecConstant())
1569 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1570
John Kessenich140f3df2015-06-26 16:58:36 -06001571 // getSymbolId() will set up all the IO decorations on the first call.
1572 // Formal function parameters were mapped during makeFunctions().
1573 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001574
1575 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1576 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001577 // Consider adding to the OpEntryPoint interface list.
1578 // Only looking at structures if they have at least one member.
1579 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1580 spv::StorageClass sc = builder.getStorageClass(id);
1581 // Before SPIR-V 1.4, we only want to include Input and Output.
1582 // Starting with SPIR-V 1.4, we want all globals.
1583 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1584 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001585 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001586 }
John Kessenich5f77d862017-09-19 11:09:59 -06001587 }
John Kessenich7ba63412015-12-20 17:37:07 -07001588 }
1589
1590 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001591 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // Prepare to generate code for the access
1593
1594 // L-value chains will be computed left to right. We're on the symbol now,
1595 // which is the left-most part of the access chain, so now is "clear" time,
1596 // followed by setting the base.
1597 builder.clearAccessChain();
1598
1599 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001600 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001601 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001602 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001603 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001604 // These are also pure R-values.
1605 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001606 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.setAccessChainRValue(id);
1608 else
1609 builder.setAccessChainLValue(id);
1610 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001611
1612 // Process linkage-only nodes for any special additional interface work.
1613 if (linkageOnly) {
1614 if (glslangIntermediate->getHlslFunctionality1()) {
1615 // Map implicit counter buffers to their originating buffers, which should have been
1616 // seen by now, given earlier pruning of unused counters, and preservation of order
1617 // of declaration.
1618 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1619 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1620 // Save possible originating buffers for counter buffers, keyed by
1621 // making the potential counter-buffer name.
1622 std::string keyName = symbol->getName().c_str();
1623 keyName = glslangIntermediate->addCounterBufferName(keyName);
1624 counterOriginator[keyName] = symbol;
1625 } else {
1626 // Handle a counter buffer, by finding the saved originating buffer.
1627 std::string keyName = symbol->getName().c_str();
1628 auto it = counterOriginator.find(keyName);
1629 if (it != counterOriginator.end()) {
1630 id = getSymbolId(it->second);
1631 if (id != spv::NoResult) {
1632 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001633 if (counterId != spv::NoResult) {
1634 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001635 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001636 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001637 }
1638 }
1639 }
1640 }
1641 }
1642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1646{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001647 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001648
qining40887662016-04-03 22:20:42 -04001649 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1650 if (node->getType().getQualifier().isSpecConstant())
1651 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 // First, handle special cases
1654 switch (node->getOp()) {
1655 case glslang::EOpAssign:
1656 case glslang::EOpAddAssign:
1657 case glslang::EOpSubAssign:
1658 case glslang::EOpMulAssign:
1659 case glslang::EOpVectorTimesMatrixAssign:
1660 case glslang::EOpVectorTimesScalarAssign:
1661 case glslang::EOpMatrixTimesScalarAssign:
1662 case glslang::EOpMatrixTimesMatrixAssign:
1663 case glslang::EOpDivAssign:
1664 case glslang::EOpModAssign:
1665 case glslang::EOpAndAssign:
1666 case glslang::EOpInclusiveOrAssign:
1667 case glslang::EOpExclusiveOrAssign:
1668 case glslang::EOpLeftShiftAssign:
1669 case glslang::EOpRightShiftAssign:
1670 // A bin-op assign "a += b" means the same thing as "a = a + b"
1671 // where a is evaluated before b. For a simple assignment, GLSL
1672 // says to evaluate the left before the right. So, always, left
1673 // node then right node.
1674 {
1675 // get the left l-value, save it away
1676 builder.clearAccessChain();
1677 node->getLeft()->traverse(this);
1678 spv::Builder::AccessChain lValue = builder.getAccessChain();
1679
1680 // evaluate the right
1681 builder.clearAccessChain();
1682 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001683 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 if (node->getOp() != glslang::EOpAssign) {
1686 // the left is also an r-value
1687 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001688 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001689
1690 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001691 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 TranslateNoContractionDecoration(node->getType().getQualifier()),
1693 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001694 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1696 node->getType().getBasicType());
1697
1698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 // store the result
1703 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001704 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // assignments are expressions having an rValue after they are evaluated...
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(rValue);
1709 }
1710 return false;
1711 case glslang::EOpIndexDirect:
1712 case glslang::EOpIndexDirectStruct:
1713 {
1714 // Get the left part of the access chain.
1715 node->getLeft()->traverse(this);
1716
1717 // Add the next element in the chain
1718
David Netoa901ffe2016-06-08 14:11:40 +01001719 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001720 if (! node->getLeft()->getType().isArray() &&
1721 node->getLeft()->getType().isVector() &&
1722 node->getOp() == glslang::EOpIndexDirect) {
1723 // This is essentially a hard-coded vector swizzle of size 1,
1724 // so short circuit the access-chain stuff with a swizzle.
1725 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001726 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001727 int dummySize;
1728 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1729 TranslateCoherent(node->getLeft()->getType()),
1730 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001732
1733 // Load through a block reference is performed with a dot operator that
1734 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1735 // do a load and reset the access chain.
1736 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1737 !node->getLeft()->getType().isArray() &&
1738 node->getOp() == glslang::EOpIndexDirectStruct)
1739 {
1740 spv::Id left = accessChainLoad(node->getLeft()->getType());
1741 builder.clearAccessChain();
1742 builder.setAccessChainLValue(left);
1743 }
1744
David Netoa901ffe2016-06-08 14:11:40 +01001745 int spvIndex = glslangIndex;
1746 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1747 node->getOp() == glslang::EOpIndexDirectStruct)
1748 {
1749 // This may be, e.g., an anonymous block-member selection, which generally need
1750 // index remapping due to hidden members in anonymous blocks.
1751 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1752 assert(remapper.size() > 0);
1753 spvIndex = remapper[glslangIndex];
1754 }
John Kessenichebb50532016-05-16 19:22:05 -06001755
David Netoa901ffe2016-06-08 14:11:40 +01001756 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001757 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001758
1759 // Add capabilities here for accessing PointSize and clip/cull distance.
1760 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001761 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001762 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764 }
1765 return false;
1766 case glslang::EOpIndexIndirect:
1767 {
1768 // Structure or array or vector indirection.
1769 // Will use native SPIR-V access-chain for struct and array indirection;
1770 // matrices are arrays of vectors, so will also work for a matrix.
1771 // Will use the access chain's 'component' for variable index into a vector.
1772
1773 // This adapter is building access chains left to right.
1774 // Set up the access chain to the left.
1775 node->getLeft()->traverse(this);
1776
1777 // save it so that computing the right side doesn't trash it
1778 spv::Builder::AccessChain partial = builder.getAccessChain();
1779
1780 // compute the next index in the chain
1781 builder.clearAccessChain();
1782 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001783 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001784
John Kessenich5611c6d2018-04-05 11:25:02 -06001785 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1786
John Kessenich140f3df2015-06-26 16:58:36 -06001787 // restore the saved access chain
1788 builder.setAccessChain(partial);
1789
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001790 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1791 int dummySize;
1792 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1793 TranslateCoherent(node->getLeft()->getType()),
1794 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1795 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001796 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001797 }
1798 return false;
1799 case glslang::EOpVectorSwizzle:
1800 {
1801 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001802 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001803 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001804 int dummySize;
1805 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1806 TranslateCoherent(node->getLeft()->getType()),
1807 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001808 }
1809 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001810 case glslang::EOpMatrixSwizzle:
1811 logger->missingFunctionality("matrix swizzle");
1812 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001813 case glslang::EOpLogicalOr:
1814 case glslang::EOpLogicalAnd:
1815 {
1816
1817 // These may require short circuiting, but can sometimes be done as straight
1818 // binary operations. The right operand must be short circuited if it has
1819 // side effects, and should probably be if it is complex.
1820 if (isTrivial(node->getRight()->getAsTyped()))
1821 break; // handle below as a normal binary operation
1822 // otherwise, we need to do dynamic short circuiting on the right operand
1823 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1824 builder.clearAccessChain();
1825 builder.setAccessChainRValue(result);
1826 }
1827 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001828 default:
1829 break;
1830 }
1831
1832 // Assume generic binary op...
1833
John Kessenich32cfd492016-02-02 12:37:46 -07001834 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001835 builder.clearAccessChain();
1836 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001837 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001838
John Kessenich32cfd492016-02-02 12:37:46 -07001839 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001840 builder.clearAccessChain();
1841 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001842 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001843
John Kessenich32cfd492016-02-02 12:37:46 -07001844 // get result
John Kessenichead86222018-03-28 18:01:20 -06001845 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001846 TranslateNoContractionDecoration(node->getType().getQualifier()),
1847 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001848 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001849 convertGlslangToSpvType(node->getType()), left, right,
1850 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001851
John Kessenich50e57562015-12-21 21:21:11 -07001852 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001853 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001854 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001855 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001856 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001857 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001858 return false;
1859 }
John Kessenich140f3df2015-06-26 16:58:36 -06001860}
1861
1862bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1863{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001864 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001865
qining40887662016-04-03 22:20:42 -04001866 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1867 if (node->getType().getQualifier().isSpecConstant())
1868 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1869
John Kessenichfc51d282015-08-19 13:34:18 -06001870 spv::Id result = spv::NoResult;
1871
1872 // try texturing first
1873 result = createImageTextureFunctionCall(node);
1874 if (result != spv::NoResult) {
1875 builder.clearAccessChain();
1876 builder.setAccessChainRValue(result);
1877
1878 return false; // done with this node
1879 }
1880
1881 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001882
1883 if (node->getOp() == glslang::EOpArrayLength) {
1884 // Quite special; won't want to evaluate the operand.
1885
John Kessenich5611c6d2018-04-05 11:25:02 -06001886 // Currently, the front-end does not allow .length() on an array until it is sized,
1887 // except for the last block membeor of an SSBO.
1888 // TODO: If this changes, link-time sized arrays might show up here, and need their
1889 // size extracted.
1890
John Kessenichc9a80832015-09-12 12:17:44 -06001891 // Normal .length() would have been constant folded by the front-end.
1892 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001893 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001894
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001895 spv::Id length;
1896 if (node->getOperand()->getType().isCoopMat()) {
1897 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1898
1899 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1900 assert(builder.isCooperativeMatrixType(typeId));
1901
1902 length = builder.createCooperativeMatrixLength(typeId);
1903 } else {
1904 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1905 block->traverse(this);
1906 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1907 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1908 }
John Kessenichc9a80832015-09-12 12:17:44 -06001909
John Kessenich8c869672018-11-28 07:01:37 -07001910 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1911 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1912 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001913 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1914 if (builder.isInSpecConstCodeGenMode()) {
1915 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1916 } else {
1917 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1918 }
1919 }
John Kessenich8c869672018-11-28 07:01:37 -07001920
John Kessenichc9a80832015-09-12 12:17:44 -06001921 builder.clearAccessChain();
1922 builder.setAccessChainRValue(length);
1923
1924 return false;
1925 }
1926
John Kessenichfc51d282015-08-19 13:34:18 -06001927 // Start by evaluating the operand
1928
John Kessenich8c8505c2016-07-26 12:50:38 -06001929 // Does it need a swizzle inversion? If so, evaluation is inverted;
1930 // operate first on the swizzle base, then apply the swizzle.
1931 spv::Id invertedType = spv::NoType;
1932 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1933 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1934 invertedType = getInvertedSwizzleType(*node->getOperand());
1935
John Kessenich140f3df2015-06-26 16:58:36 -06001936 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001937 if (invertedType != spv::NoType)
1938 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1939 else
1940 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001941
Rex Xufc618912015-09-09 16:42:49 +08001942 spv::Id operand = spv::NoResult;
1943
1944 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1945 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001946 node->getOp() == glslang::EOpAtomicCounter ||
1947 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001948 operand = builder.accessChainGetLValue(); // Special case l-value operands
1949 else
John Kessenich32cfd492016-02-02 12:37:46 -07001950 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenichead86222018-03-28 18:01:20 -06001952 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001953 TranslateNoContractionDecoration(node->getType().getQualifier()),
1954 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001955
1956 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001957 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001958 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001959
1960 // if not, then possibly an operation
1961 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001962 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001963
1964 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001965 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001966 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001967 builder.addDecoration(result, decorations.nonUniform);
1968 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001969
John Kessenich140f3df2015-06-26 16:58:36 -06001970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(result);
1972
1973 return false; // done with this node
1974 }
1975
1976 // it must be a special case, check...
1977 switch (node->getOp()) {
1978 case glslang::EOpPostIncrement:
1979 case glslang::EOpPostDecrement:
1980 case glslang::EOpPreIncrement:
1981 case glslang::EOpPreDecrement:
1982 {
1983 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001984 spv::Id one = 0;
1985 if (node->getBasicType() == glslang::EbtFloat)
1986 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001987 else if (node->getBasicType() == glslang::EbtDouble)
1988 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001989 else if (node->getBasicType() == glslang::EbtFloat16)
1990 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001991 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1992 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001993 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1994 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001995 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1996 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001997 else
1998 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001999 glslang::TOperator op;
2000 if (node->getOp() == glslang::EOpPreIncrement ||
2001 node->getOp() == glslang::EOpPostIncrement)
2002 op = glslang::EOpAdd;
2003 else
2004 op = glslang::EOpSub;
2005
John Kessenichead86222018-03-28 18:01:20 -06002006 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002007 convertGlslangToSpvType(node->getType()), operand, one,
2008 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002009 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002010
2011 // The result of operation is always stored, but conditionally the
2012 // consumed result. The consumed result is always an r-value.
2013 builder.accessChainStore(result);
2014 builder.clearAccessChain();
2015 if (node->getOp() == glslang::EOpPreIncrement ||
2016 node->getOp() == glslang::EOpPreDecrement)
2017 builder.setAccessChainRValue(result);
2018 else
2019 builder.setAccessChainRValue(operand);
2020 }
2021
2022 return false;
2023
2024 case glslang::EOpEmitStreamVertex:
2025 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2026 return false;
2027 case glslang::EOpEndStreamPrimitive:
2028 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2029 return false;
2030
2031 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002032 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002033 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002034 }
John Kessenich140f3df2015-06-26 16:58:36 -06002035}
2036
2037bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2038{
qining27e04a02016-04-14 16:40:20 -04002039 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2040 if (node->getType().getQualifier().isSpecConstant())
2041 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2042
John Kessenichfc51d282015-08-19 13:34:18 -06002043 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002044 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2045 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002046
2047 // try texturing
2048 result = createImageTextureFunctionCall(node);
2049 if (result != spv::NoResult) {
2050 builder.clearAccessChain();
2051 builder.setAccessChainRValue(result);
2052
2053 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002054 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002055#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002056 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002057#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002058 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002059 // "imageStore" is a special case, which has no result
2060 return false;
2061 }
John Kessenichfc51d282015-08-19 13:34:18 -06002062
John Kessenich140f3df2015-06-26 16:58:36 -06002063 glslang::TOperator binOp = glslang::EOpNull;
2064 bool reduceComparison = true;
2065 bool isMatrix = false;
2066 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002067 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002068
2069 assert(node->getOp());
2070
John Kessenichf6640762016-08-01 19:44:00 -06002071 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002072
2073 switch (node->getOp()) {
2074 case glslang::EOpSequence:
2075 {
2076 if (preVisit)
2077 ++sequenceDepth;
2078 else
2079 --sequenceDepth;
2080
2081 if (sequenceDepth == 1) {
2082 // If this is the parent node of all the functions, we want to see them
2083 // early, so all call points have actual SPIR-V functions to reference.
2084 // In all cases, still let the traverser visit the children for us.
2085 makeFunctions(node->getAsAggregate()->getSequence());
2086
John Kessenich6fccb3c2016-09-19 16:01:41 -06002087 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002088 // anything else gets there, so visit out of order, doing them all now.
2089 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2090
John Kessenich6a60c2f2016-12-08 21:01:59 -07002091 // 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 -06002092 // so do them manually.
2093 visitFunctions(node->getAsAggregate()->getSequence());
2094
2095 return false;
2096 }
2097
2098 return true;
2099 }
2100 case glslang::EOpLinkerObjects:
2101 {
2102 if (visit == glslang::EvPreVisit)
2103 linkageOnly = true;
2104 else
2105 linkageOnly = false;
2106
2107 return true;
2108 }
2109 case glslang::EOpComma:
2110 {
2111 // processing from left to right naturally leaves the right-most
2112 // lying around in the access chain
2113 glslang::TIntermSequence& glslangOperands = node->getSequence();
2114 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2115 glslangOperands[i]->traverse(this);
2116
2117 return false;
2118 }
2119 case glslang::EOpFunction:
2120 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002121 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002122 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002123 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002124 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002125 } else {
2126 handleFunctionEntry(node);
2127 }
2128 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002129 if (inEntryPoint)
2130 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002131 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002132 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002133 }
2134
2135 return true;
2136 case glslang::EOpParameters:
2137 // Parameters will have been consumed by EOpFunction processing, but not
2138 // the body, so we still visited the function node's children, making this
2139 // child redundant.
2140 return false;
2141 case glslang::EOpFunctionCall:
2142 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002143 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002144 if (node->isUserDefined())
2145 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002146 // 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 -07002147 if (result) {
2148 builder.clearAccessChain();
2149 builder.setAccessChainRValue(result);
2150 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002151 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002152
2153 return false;
2154 }
2155 case glslang::EOpConstructMat2x2:
2156 case glslang::EOpConstructMat2x3:
2157 case glslang::EOpConstructMat2x4:
2158 case glslang::EOpConstructMat3x2:
2159 case glslang::EOpConstructMat3x3:
2160 case glslang::EOpConstructMat3x4:
2161 case glslang::EOpConstructMat4x2:
2162 case glslang::EOpConstructMat4x3:
2163 case glslang::EOpConstructMat4x4:
2164 case glslang::EOpConstructDMat2x2:
2165 case glslang::EOpConstructDMat2x3:
2166 case glslang::EOpConstructDMat2x4:
2167 case glslang::EOpConstructDMat3x2:
2168 case glslang::EOpConstructDMat3x3:
2169 case glslang::EOpConstructDMat3x4:
2170 case glslang::EOpConstructDMat4x2:
2171 case glslang::EOpConstructDMat4x3:
2172 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002173 case glslang::EOpConstructIMat2x2:
2174 case glslang::EOpConstructIMat2x3:
2175 case glslang::EOpConstructIMat2x4:
2176 case glslang::EOpConstructIMat3x2:
2177 case glslang::EOpConstructIMat3x3:
2178 case glslang::EOpConstructIMat3x4:
2179 case glslang::EOpConstructIMat4x2:
2180 case glslang::EOpConstructIMat4x3:
2181 case glslang::EOpConstructIMat4x4:
2182 case glslang::EOpConstructUMat2x2:
2183 case glslang::EOpConstructUMat2x3:
2184 case glslang::EOpConstructUMat2x4:
2185 case glslang::EOpConstructUMat3x2:
2186 case glslang::EOpConstructUMat3x3:
2187 case glslang::EOpConstructUMat3x4:
2188 case glslang::EOpConstructUMat4x2:
2189 case glslang::EOpConstructUMat4x3:
2190 case glslang::EOpConstructUMat4x4:
2191 case glslang::EOpConstructBMat2x2:
2192 case glslang::EOpConstructBMat2x3:
2193 case glslang::EOpConstructBMat2x4:
2194 case glslang::EOpConstructBMat3x2:
2195 case glslang::EOpConstructBMat3x3:
2196 case glslang::EOpConstructBMat3x4:
2197 case glslang::EOpConstructBMat4x2:
2198 case glslang::EOpConstructBMat4x3:
2199 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002200 case glslang::EOpConstructF16Mat2x2:
2201 case glslang::EOpConstructF16Mat2x3:
2202 case glslang::EOpConstructF16Mat2x4:
2203 case glslang::EOpConstructF16Mat3x2:
2204 case glslang::EOpConstructF16Mat3x3:
2205 case glslang::EOpConstructF16Mat3x4:
2206 case glslang::EOpConstructF16Mat4x2:
2207 case glslang::EOpConstructF16Mat4x3:
2208 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002209 isMatrix = true;
2210 // fall through
2211 case glslang::EOpConstructFloat:
2212 case glslang::EOpConstructVec2:
2213 case glslang::EOpConstructVec3:
2214 case glslang::EOpConstructVec4:
2215 case glslang::EOpConstructDouble:
2216 case glslang::EOpConstructDVec2:
2217 case glslang::EOpConstructDVec3:
2218 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002219 case glslang::EOpConstructFloat16:
2220 case glslang::EOpConstructF16Vec2:
2221 case glslang::EOpConstructF16Vec3:
2222 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002223 case glslang::EOpConstructBool:
2224 case glslang::EOpConstructBVec2:
2225 case glslang::EOpConstructBVec3:
2226 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002227 case glslang::EOpConstructInt8:
2228 case glslang::EOpConstructI8Vec2:
2229 case glslang::EOpConstructI8Vec3:
2230 case glslang::EOpConstructI8Vec4:
2231 case glslang::EOpConstructUint8:
2232 case glslang::EOpConstructU8Vec2:
2233 case glslang::EOpConstructU8Vec3:
2234 case glslang::EOpConstructU8Vec4:
2235 case glslang::EOpConstructInt16:
2236 case glslang::EOpConstructI16Vec2:
2237 case glslang::EOpConstructI16Vec3:
2238 case glslang::EOpConstructI16Vec4:
2239 case glslang::EOpConstructUint16:
2240 case glslang::EOpConstructU16Vec2:
2241 case glslang::EOpConstructU16Vec3:
2242 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002243 case glslang::EOpConstructInt:
2244 case glslang::EOpConstructIVec2:
2245 case glslang::EOpConstructIVec3:
2246 case glslang::EOpConstructIVec4:
2247 case glslang::EOpConstructUint:
2248 case glslang::EOpConstructUVec2:
2249 case glslang::EOpConstructUVec3:
2250 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002251 case glslang::EOpConstructInt64:
2252 case glslang::EOpConstructI64Vec2:
2253 case glslang::EOpConstructI64Vec3:
2254 case glslang::EOpConstructI64Vec4:
2255 case glslang::EOpConstructUint64:
2256 case glslang::EOpConstructU64Vec2:
2257 case glslang::EOpConstructU64Vec3:
2258 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002259 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002260 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002261 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002262 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002263 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002264 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002265 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002266 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002267 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002268 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002269 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002270 else if (node->getOp() == glslang::EOpConstructStruct ||
2271 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2272 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002273 std::vector<spv::Id> constituents;
2274 for (int c = 0; c < (int)arguments.size(); ++c)
2275 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002276 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002277 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002278 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002279 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002281
2282 builder.clearAccessChain();
2283 builder.setAccessChainRValue(constructed);
2284
2285 return false;
2286 }
2287
2288 // These six are component-wise compares with component-wise results.
2289 // Forward on to createBinaryOperation(), requesting a vector result.
2290 case glslang::EOpLessThan:
2291 case glslang::EOpGreaterThan:
2292 case glslang::EOpLessThanEqual:
2293 case glslang::EOpGreaterThanEqual:
2294 case glslang::EOpVectorEqual:
2295 case glslang::EOpVectorNotEqual:
2296 {
2297 // Map the operation to a binary
2298 binOp = node->getOp();
2299 reduceComparison = false;
2300 switch (node->getOp()) {
2301 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2302 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2303 default: binOp = node->getOp(); break;
2304 }
2305
2306 break;
2307 }
2308 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002309 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002310 binOp = glslang::EOpMul;
2311 break;
2312 case glslang::EOpOuterProduct:
2313 // two vectors multiplied to make a matrix
2314 binOp = glslang::EOpOuterProduct;
2315 break;
2316 case glslang::EOpDot:
2317 {
qining25262b32016-05-06 17:25:16 -04002318 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002319 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002320 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002321 binOp = glslang::EOpMul;
2322 break;
2323 }
2324 case glslang::EOpMod:
2325 // when an aggregate, this is the floating-point mod built-in function,
2326 // which can be emitted by the one in createBinaryOperation()
2327 binOp = glslang::EOpMod;
2328 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002329 case glslang::EOpEmitVertex:
2330 case glslang::EOpEndPrimitive:
2331 case glslang::EOpBarrier:
2332 case glslang::EOpMemoryBarrier:
2333 case glslang::EOpMemoryBarrierAtomicCounter:
2334 case glslang::EOpMemoryBarrierBuffer:
2335 case glslang::EOpMemoryBarrierImage:
2336 case glslang::EOpMemoryBarrierShared:
2337 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002338 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002339 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002340 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002341 case glslang::EOpWorkgroupMemoryBarrier:
2342 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002343 case glslang::EOpSubgroupBarrier:
2344 case glslang::EOpSubgroupMemoryBarrier:
2345 case glslang::EOpSubgroupMemoryBarrierBuffer:
2346 case glslang::EOpSubgroupMemoryBarrierImage:
2347 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002348 noReturnValue = true;
2349 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2350 break;
2351
Jeff Bolz36831c92018-09-05 10:11:41 -05002352 case glslang::EOpAtomicStore:
2353 noReturnValue = true;
2354 // fallthrough
2355 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002356 case glslang::EOpAtomicAdd:
2357 case glslang::EOpAtomicMin:
2358 case glslang::EOpAtomicMax:
2359 case glslang::EOpAtomicAnd:
2360 case glslang::EOpAtomicOr:
2361 case glslang::EOpAtomicXor:
2362 case glslang::EOpAtomicExchange:
2363 case glslang::EOpAtomicCompSwap:
2364 atomic = true;
2365 break;
2366
John Kessenich0d0c6d32017-07-23 16:08:26 -06002367 case glslang::EOpAtomicCounterAdd:
2368 case glslang::EOpAtomicCounterSubtract:
2369 case glslang::EOpAtomicCounterMin:
2370 case glslang::EOpAtomicCounterMax:
2371 case glslang::EOpAtomicCounterAnd:
2372 case glslang::EOpAtomicCounterOr:
2373 case glslang::EOpAtomicCounterXor:
2374 case glslang::EOpAtomicCounterExchange:
2375 case glslang::EOpAtomicCounterCompSwap:
2376 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2377 builder.addCapability(spv::CapabilityAtomicStorageOps);
2378 atomic = true;
2379 break;
2380
Chao Chen3c366992018-09-19 11:41:59 -07002381#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002382 case glslang::EOpIgnoreIntersectionNV:
2383 case glslang::EOpTerminateRayNV:
2384 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002385 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002386 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2387 noReturnValue = true;
2388 break;
2389#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002390 case glslang::EOpCooperativeMatrixLoad:
2391 case glslang::EOpCooperativeMatrixStore:
2392 noReturnValue = true;
2393 break;
Chao Chen3c366992018-09-19 11:41:59 -07002394
John Kessenich140f3df2015-06-26 16:58:36 -06002395 default:
2396 break;
2397 }
2398
2399 //
2400 // See if it maps to a regular operation.
2401 //
John Kessenich140f3df2015-06-26 16:58:36 -06002402 if (binOp != glslang::EOpNull) {
2403 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2404 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2405 assert(left && right);
2406
2407 builder.clearAccessChain();
2408 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002409 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002410
2411 builder.clearAccessChain();
2412 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002413 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002414
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002415 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002416 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002417 TranslateNoContractionDecoration(node->getType().getQualifier()),
2418 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002419 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002420 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002421 left->getType().getBasicType(), reduceComparison);
2422
2423 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002424 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002425 builder.clearAccessChain();
2426 builder.setAccessChainRValue(result);
2427
2428 return false;
2429 }
2430
John Kessenich426394d2015-07-23 10:22:48 -06002431 //
2432 // Create the list of operands.
2433 //
John Kessenich140f3df2015-06-26 16:58:36 -06002434 glslang::TIntermSequence& glslangOperands = node->getSequence();
2435 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002436 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002437 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002438 // special case l-value operands; there are just a few
2439 bool lvalue = false;
2440 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002441 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002442 case glslang::EOpModf:
2443 if (arg == 1)
2444 lvalue = true;
2445 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002446 case glslang::EOpInterpolateAtSample:
2447 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002448#ifdef AMD_EXTENSIONS
2449 case glslang::EOpInterpolateAtVertex:
2450#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002451 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002452 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002453
2454 // Does it need a swizzle inversion? If so, evaluation is inverted;
2455 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002456 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002457 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2458 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2459 }
Rex Xu7a26c172015-12-08 17:12:09 +08002460 break;
Rex Xud4782c12015-09-06 16:30:11 +08002461 case glslang::EOpAtomicAdd:
2462 case glslang::EOpAtomicMin:
2463 case glslang::EOpAtomicMax:
2464 case glslang::EOpAtomicAnd:
2465 case glslang::EOpAtomicOr:
2466 case glslang::EOpAtomicXor:
2467 case glslang::EOpAtomicExchange:
2468 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002469 case glslang::EOpAtomicLoad:
2470 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002471 case glslang::EOpAtomicCounterAdd:
2472 case glslang::EOpAtomicCounterSubtract:
2473 case glslang::EOpAtomicCounterMin:
2474 case glslang::EOpAtomicCounterMax:
2475 case glslang::EOpAtomicCounterAnd:
2476 case glslang::EOpAtomicCounterOr:
2477 case glslang::EOpAtomicCounterXor:
2478 case glslang::EOpAtomicCounterExchange:
2479 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002480 if (arg == 0)
2481 lvalue = true;
2482 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002483 case glslang::EOpAddCarry:
2484 case glslang::EOpSubBorrow:
2485 if (arg == 2)
2486 lvalue = true;
2487 break;
2488 case glslang::EOpUMulExtended:
2489 case glslang::EOpIMulExtended:
2490 if (arg >= 2)
2491 lvalue = true;
2492 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002493 case glslang::EOpCooperativeMatrixLoad:
2494 if (arg == 0 || arg == 1)
2495 lvalue = true;
2496 break;
2497 case glslang::EOpCooperativeMatrixStore:
2498 if (arg == 1)
2499 lvalue = true;
2500 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002501 default:
2502 break;
2503 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002504 builder.clearAccessChain();
2505 if (invertedType != spv::NoType && arg == 0)
2506 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2507 else
2508 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002509
2510 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2511 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2512
2513 if (arg == 1) {
2514 // fold "element" parameter into the access chain
2515 spv::Builder::AccessChain save = builder.getAccessChain();
2516 builder.clearAccessChain();
2517 glslangOperands[2]->traverse(this);
2518
2519 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2520
2521 builder.setAccessChain(save);
2522
2523 // Point to the first element of the array.
2524 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002525 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002526
2527 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2528 unsigned int alignment = builder.getAccessChain().alignment;
2529
2530 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2531 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2532 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2533 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2534 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2535 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2536 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2537 }
2538
2539 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2540
2541 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2542 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2543 }
2544
2545 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2546 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2547 }
2548 } else if (arg == 2) {
2549 continue;
2550 }
2551 }
2552
John Kessenich140f3df2015-06-26 16:58:36 -06002553 if (lvalue)
2554 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002555 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002556 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002557 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002558 }
John Kessenich140f3df2015-06-26 16:58:36 -06002559 }
John Kessenich426394d2015-07-23 10:22:48 -06002560
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002561 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002562 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2563 std::vector<spv::IdImmediate> idImmOps;
2564
2565 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2566 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2567 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2568 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2569 // get the pointee type
2570 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2571 assert(builder.isCooperativeMatrixType(typeId));
2572 // do the op
2573 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2574 // store the result to the pointer (out param 'm')
2575 builder.createStore(result, operands[0]);
2576 result = 0;
2577 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2578 std::vector<spv::IdImmediate> idImmOps;
2579
2580 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2581 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2582 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2583 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2584 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2585
2586 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2587 result = 0;
2588 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002589 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002591 } else {
2592 // Pass through to generic operations.
2593 switch (glslangOperands.size()) {
2594 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002595 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002596 break;
2597 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002598 {
2599 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002600 TranslateNoContractionDecoration(node->getType().getQualifier()),
2601 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002602 result = createUnaryOperation(
2603 node->getOp(), decorations,
2604 resultType(), operands.front(),
2605 glslangOperands[0]->getAsTyped()->getBasicType());
2606 }
John Kessenich426394d2015-07-23 10:22:48 -06002607 break;
2608 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002609 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002610 break;
2611 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002612 if (invertedType)
2613 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002614 }
2615
2616 if (noReturnValue)
2617 return false;
2618
2619 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002620 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002621 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002622 } else {
2623 builder.clearAccessChain();
2624 builder.setAccessChainRValue(result);
2625 return false;
2626 }
2627}
2628
John Kessenich433e9ff2017-01-26 20:31:11 -07002629// This path handles both if-then-else and ?:
2630// The if-then-else has a node type of void, while
2631// ?: has either a void or a non-void node type
2632//
2633// Leaving the result, when not void:
2634// GLSL only has r-values as the result of a :?, but
2635// if we have an l-value, that can be more efficient if it will
2636// become the base of a complex r-value expression, because the
2637// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002638bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2639{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002640 // see if OpSelect can handle it
2641 const auto isOpSelectable = [&]() {
2642 if (node->getBasicType() == glslang::EbtVoid)
2643 return false;
2644 // OpSelect can do all other types starting with SPV 1.4
2645 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2646 // pre-1.4, only scalars and vectors can be handled
2647 if ((!node->getType().isScalar() && !node->getType().isVector()))
2648 return false;
2649 }
2650 return true;
2651 };
2652
John Kessenich4bee5312018-02-20 21:29:05 -07002653 // See if it simple and safe, or required, to execute both sides.
2654 // Crucially, side effects must be either semantically required or avoided,
2655 // and there are performance trade-offs.
2656 // Return true if required or a good idea (and safe) to execute both sides,
2657 // false otherwise.
2658 const auto bothSidesPolicy = [&]() -> bool {
2659 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002660 if (node->getTrueBlock() == nullptr ||
2661 node->getFalseBlock() == nullptr)
2662 return false;
2663
John Kessenich4bee5312018-02-20 21:29:05 -07002664 // required? (unless we write additional code to look for side effects
2665 // and make performance trade-offs if none are present)
2666 if (!node->getShortCircuit())
2667 return true;
2668
2669 // if not required to execute both, decide based on performance/practicality...
2670
John Kessenich0c1e71a2019-01-10 18:23:06 +07002671 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002672 return false;
2673
John Kessenich433e9ff2017-01-26 20:31:11 -07002674 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2675 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2676
2677 // return true if a single operand to ? : is okay for OpSelect
2678 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002679 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002680 };
2681
2682 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2683 operandOkay(node->getFalseBlock()->getAsTyped());
2684 };
2685
John Kessenich4bee5312018-02-20 21:29:05 -07002686 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2687 // emit the condition before doing anything with selection
2688 node->getCondition()->traverse(this);
2689 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2690
2691 // Find a way of executing both sides and selecting the right result.
2692 const auto executeBothSides = [&]() -> void {
2693 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002694 node->getTrueBlock()->traverse(this);
2695 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2696 node->getFalseBlock()->traverse(this);
2697 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2698
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002699 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002700
John Kessenich4bee5312018-02-20 21:29:05 -07002701 // done if void
2702 if (node->getBasicType() == glslang::EbtVoid)
2703 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002704
John Kessenich4bee5312018-02-20 21:29:05 -07002705 // emit code to select between trueValue and falseValue
2706
2707 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002708 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002709 // Emit OpSelect for this selection.
2710
2711 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002712 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2713 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002714 condition = builder.smearScalar(spv::NoPrecision, condition,
2715 builder.makeVectorType(builder.makeBoolType(),
2716 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002717 }
John Kessenich4bee5312018-02-20 21:29:05 -07002718
2719 // OpSelect
2720 result = builder.createTriOp(spv::OpSelect,
2721 convertGlslangToSpvType(node->getType()), condition,
2722 trueValue, falseValue);
2723
2724 builder.clearAccessChain();
2725 builder.setAccessChainRValue(result);
2726 } else {
2727 // We need control flow to select the result.
2728 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2729 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2730
2731 // Selection control:
2732 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2733
2734 // make an "if" based on the value created by the condition
2735 spv::Builder::If ifBuilder(condition, control, builder);
2736
2737 // emit the "then" statement
2738 builder.createStore(trueValue, result);
2739 ifBuilder.makeBeginElse();
2740 // emit the "else" statement
2741 builder.createStore(falseValue, result);
2742
2743 // finish off the control flow
2744 ifBuilder.makeEndIf();
2745
2746 builder.clearAccessChain();
2747 builder.setAccessChainLValue(result);
2748 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002749 };
2750
John Kessenich4bee5312018-02-20 21:29:05 -07002751 // Execute the one side needed, as per the condition
2752 const auto executeOneSide = [&]() {
2753 // Always emit control flow.
2754 if (node->getBasicType() != glslang::EbtVoid)
2755 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002756
John Kessenich4bee5312018-02-20 21:29:05 -07002757 // Selection control:
2758 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2759
2760 // make an "if" based on the value created by the condition
2761 spv::Builder::If ifBuilder(condition, control, builder);
2762
2763 // emit the "then" statement
2764 if (node->getTrueBlock() != nullptr) {
2765 node->getTrueBlock()->traverse(this);
2766 if (result != spv::NoResult)
2767 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2768 }
2769
2770 if (node->getFalseBlock() != nullptr) {
2771 ifBuilder.makeBeginElse();
2772 // emit the "else" statement
2773 node->getFalseBlock()->traverse(this);
2774 if (result != spv::NoResult)
2775 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2776 }
2777
2778 // finish off the control flow
2779 ifBuilder.makeEndIf();
2780
2781 if (result != spv::NoResult) {
2782 builder.clearAccessChain();
2783 builder.setAccessChainLValue(result);
2784 }
2785 };
2786
2787 // Try for OpSelect (or a requirement to execute both sides)
2788 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002789 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2790 if (node->getType().getQualifier().isSpecConstant())
2791 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002792 executeBothSides();
2793 } else
2794 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002795
2796 return false;
2797}
2798
2799bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2800{
2801 // emit and get the condition before doing anything with switch
2802 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002803 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002804
Rex Xu57e65922017-07-04 23:23:40 +08002805 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002806 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002807
John Kessenich140f3df2015-06-26 16:58:36 -06002808 // browse the children to sort out code segments
2809 int defaultSegment = -1;
2810 std::vector<TIntermNode*> codeSegments;
2811 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2812 std::vector<int> caseValues;
2813 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2814 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2815 TIntermNode* child = *c;
2816 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002817 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002818 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002819 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002820 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2821 } else
2822 codeSegments.push_back(child);
2823 }
2824
qining25262b32016-05-06 17:25:16 -04002825 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002826 // statements between the last case and the end of the switch statement
2827 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2828 (int)codeSegments.size() == defaultSegment)
2829 codeSegments.push_back(nullptr);
2830
2831 // make the switch statement
2832 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002833 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002834
2835 // emit all the code in the segments
2836 breakForLoop.push(false);
2837 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2838 builder.nextSwitchSegment(segmentBlocks, s);
2839 if (codeSegments[s])
2840 codeSegments[s]->traverse(this);
2841 else
2842 builder.addSwitchBreak();
2843 }
2844 breakForLoop.pop();
2845
2846 builder.endSwitch(segmentBlocks);
2847
2848 return false;
2849}
2850
2851void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2852{
2853 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002854 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002855
2856 builder.clearAccessChain();
2857 builder.setAccessChainRValue(constant);
2858}
2859
2860bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2861{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002862 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002863 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002864
2865 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002866 std::vector<unsigned int> operands;
2867 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002868
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002869 // Spec requires back edges to target header blocks, and every header block
2870 // must dominate its merge block. Make a header block first to ensure these
2871 // conditions are met. By definition, it will contain OpLoopMerge, followed
2872 // by a block-ending branch. But we don't want to put any other body/test
2873 // instructions in it, since the body/test may have arbitrary instructions,
2874 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002875 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002876 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002877 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002878 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002879 spv::Block& test = builder.makeNewBlock();
2880 builder.createBranch(&test);
2881
2882 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002883 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002884 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002885 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2886
2887 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002888 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002889 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002890 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002891 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002892 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002893
2894 builder.setBuildPoint(&blocks.continue_target);
2895 if (node->getTerminal())
2896 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002897 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002898 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002899 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002900 builder.createBranch(&blocks.body);
2901
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002902 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002903 builder.setBuildPoint(&blocks.body);
2904 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002905 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002906 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002907 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002908
2909 builder.setBuildPoint(&blocks.continue_target);
2910 if (node->getTerminal())
2911 node->getTerminal()->traverse(this);
2912 if (node->getTest()) {
2913 node->getTest()->traverse(this);
2914 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002915 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002916 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002917 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002918 // TODO: unless there was a break/return/discard instruction
2919 // somewhere in the body, this is an infinite loop, so we should
2920 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002921 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002922 }
John Kessenich140f3df2015-06-26 16:58:36 -06002923 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002924 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002925 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002926 return false;
2927}
2928
2929bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2930{
2931 if (node->getExpression())
2932 node->getExpression()->traverse(this);
2933
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002934 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002935
John Kessenich140f3df2015-06-26 16:58:36 -06002936 switch (node->getFlowOp()) {
2937 case glslang::EOpKill:
2938 builder.makeDiscard();
2939 break;
2940 case glslang::EOpBreak:
2941 if (breakForLoop.top())
2942 builder.createLoopExit();
2943 else
2944 builder.addSwitchBreak();
2945 break;
2946 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002947 builder.createLoopContinue();
2948 break;
2949 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002950 if (node->getExpression()) {
2951 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2952 spv::Id returnId = accessChainLoad(glslangReturnType);
2953 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2954 builder.clearAccessChain();
2955 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2956 builder.setAccessChainLValue(copyId);
2957 multiTypeStore(glslangReturnType, returnId);
2958 returnId = builder.createLoad(copyId);
2959 }
2960 builder.makeReturn(false, returnId);
2961 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002962 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002963
2964 builder.clearAccessChain();
2965 break;
2966
2967 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002968 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 }
2971
2972 return false;
2973}
2974
2975spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2976{
qining25262b32016-05-06 17:25:16 -04002977 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002978 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002979 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002980 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002981 spv::Id result = createSpvConstant(*node);
2982 if (result != spv::NoResult)
2983 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 }
2985
2986 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002987 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002988 spv::Id spvType = convertGlslangToSpvType(node->getType());
2989
Rex Xucabbb782017-03-24 13:41:14 +08002990 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2991 node->getType().containsBasicType(glslang::EbtInt16) ||
2992 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002993 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002994 switch (storageClass) {
2995 case spv::StorageClassInput:
2996 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002997 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002998 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002999 break;
3000 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003001 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003002 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003003 break;
3004 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003005 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003006 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3007 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003008 else
3009 builder.addCapability(spv::CapabilityStorageUniform16);
3010 break;
3011 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003012 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003013 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3014 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3015 break;
3016 default:
3017 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003018 }
3019 }
Rex Xuf89ad982017-04-07 23:22:33 +08003020
John Kessenich312dcfb2018-07-03 13:19:51 -06003021 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3022 node->getType().containsBasicType(glslang::EbtUint8);
3023 if (contains8BitType) {
3024 if (storageClass == spv::StorageClassPushConstant) {
3025 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3026 builder.addCapability(spv::CapabilityStoragePushConstant8);
3027 } else if (storageClass == spv::StorageClassUniform) {
3028 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3029 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003030 } else if (storageClass == spv::StorageClassStorageBuffer) {
3031 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3032 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003033 }
3034 }
3035
John Kessenich140f3df2015-06-26 16:58:36 -06003036 const char* name = node->getName().c_str();
3037 if (glslang::IsAnonymous(name))
3038 name = "";
3039
3040 return builder.createVariable(storageClass, spvType, name);
3041}
3042
3043// Return type Id of the sampled type.
3044spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3045{
3046 switch (sampler.type) {
3047 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003048#ifdef AMD_EXTENSIONS
3049 case glslang::EbtFloat16:
3050 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3051 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3052 return builder.makeFloatType(16);
3053#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003054 case glslang::EbtInt: return builder.makeIntType(32);
3055 case glslang::EbtUint: return builder.makeUintType(32);
3056 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003057 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003058 return builder.makeFloatType(32);
3059 }
3060}
3061
John Kessenich8c8505c2016-07-26 12:50:38 -06003062// If node is a swizzle operation, return the type that should be used if
3063// the swizzle base is first consumed by another operation, before the swizzle
3064// is applied.
3065spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3066{
John Kessenichecba76f2017-01-06 00:34:48 -07003067 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003068 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3069 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3070 else
3071 return spv::NoType;
3072}
3073
3074// When inverting a swizzle with a parent op, this function
3075// will apply the swizzle operation to a completed parent operation.
3076spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3077{
3078 std::vector<unsigned> swizzle;
3079 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3080 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3081}
3082
John Kessenich8c8505c2016-07-26 12:50:38 -06003083// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3084void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3085{
3086 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3087 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3088 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3089}
3090
John Kessenich3ac051e2015-12-20 11:29:16 -07003091// Convert from a glslang type to an SPV type, by calling into a
3092// recursive version of this function. This establishes the inherited
3093// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003094spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003095{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003096 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003097}
3098
3099// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003100// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003101// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003102spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003103 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3104 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003105{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003106 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003107
3108 switch (type.getBasicType()) {
3109 case glslang::EbtVoid:
3110 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003111 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113 case glslang::EbtFloat:
3114 spvType = builder.makeFloatType(32);
3115 break;
3116 case glslang::EbtDouble:
3117 spvType = builder.makeFloatType(64);
3118 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003119 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003120 spvType = builder.makeFloatType(16);
3121 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003123 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3124 // a 32-bit int where non-0 means true.
3125 if (explicitLayout != glslang::ElpNone)
3126 spvType = builder.makeUintType(32);
3127 else
3128 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003130 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003131 spvType = builder.makeIntType(8);
3132 break;
3133 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003134 spvType = builder.makeUintType(8);
3135 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003136 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003137 spvType = builder.makeIntType(16);
3138 break;
3139 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003140 spvType = builder.makeUintType(16);
3141 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 case glslang::EbtInt:
3143 spvType = builder.makeIntType(32);
3144 break;
3145 case glslang::EbtUint:
3146 spvType = builder.makeUintType(32);
3147 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003148 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003149 spvType = builder.makeIntType(64);
3150 break;
3151 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003152 spvType = builder.makeUintType(64);
3153 break;
John Kessenich426394d2015-07-23 10:22:48 -06003154 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003155 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003156 spvType = builder.makeUintType(32);
3157 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003158#ifdef NV_EXTENSIONS
3159 case glslang::EbtAccStructNV:
3160 spvType = builder.makeAccelerationStructureNVType();
3161 break;
3162#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003163 case glslang::EbtSampler:
3164 {
3165 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003166 if (sampler.sampler) {
3167 // pure sampler
3168 spvType = builder.makeSamplerType();
3169 } else {
3170 // an image is present, make its type
3171 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3172 sampler.image ? 2 : 1, TranslateImageFormat(type));
3173 if (sampler.combined) {
3174 // already has both image and sampler, make the combined type
3175 spvType = builder.makeSampledImageType(spvType);
3176 }
John Kessenich55e7d112015-11-15 21:33:39 -07003177 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003178 }
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EbtStruct:
3181 case glslang::EbtBlock:
3182 {
3183 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003184 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003185
3186 // Try to share structs for different layouts, but not yet for other
3187 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003188 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003189 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003190 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192
3193 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003194 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003195 memberRemapper[glslangMembers].resize(glslangMembers->size());
3196 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003197 }
3198 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003199 case glslang::EbtReference:
3200 {
3201 // Make the forward pointer, then recurse to convert the structure type, then
3202 // patch up the forward pointer with a real pointer type.
3203 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3204 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3205 forwardPointers[type.getReferentType()] = forwardId;
3206 }
3207 spvType = forwardPointers[type.getReferentType()];
3208 if (!forwardReferenceOnly) {
3209 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3210 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3211 forwardPointers[type.getReferentType()],
3212 referentType);
3213 }
3214 }
3215 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003218 break;
3219 }
3220
3221 if (type.isMatrix())
3222 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3223 else {
3224 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3225 if (type.getVectorSize() > 1)
3226 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3227 }
3228
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003229 if (type.isCoopMat()) {
3230 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3231 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3232 if (type.getBasicType() == glslang::EbtFloat16)
3233 builder.addCapability(spv::CapabilityFloat16);
3234
3235 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3236 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3237 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3238
3239 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3240 }
3241
John Kessenich140f3df2015-06-26 16:58:36 -06003242 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003243 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3244
John Kessenichc9a80832015-09-12 12:17:44 -06003245 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003246 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003247 // We need to decorate array strides for types needing explicit layout, except blocks.
3248 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003249 // Use a dummy glslang type for querying internal strides of
3250 // arrays of arrays, but using just a one-dimensional array.
3251 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003252 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3253 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003254
3255 // Will compute the higher-order strides here, rather than making a whole
3256 // pile of types and doing repetitive recursion on their contents.
3257 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3258 }
John Kessenichf8842e52016-01-04 19:22:56 -07003259
3260 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003261 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003262 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003263 if (stride > 0)
3264 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003265 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003266 }
3267 } else {
3268 // single-dimensional array, and don't yet have stride
3269
John Kessenichf8842e52016-01-04 19:22:56 -07003270 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003271 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3272 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003273 }
John Kessenich31ed4832015-09-09 17:51:38 -06003274
John Kessenichead86222018-03-28 18:01:20 -06003275 // Do the outer dimension, which might not be known for a runtime-sized array.
3276 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3277 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003278 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003279 else {
3280 if (!lastBufferBlockMember) {
3281 builder.addExtension("SPV_EXT_descriptor_indexing");
3282 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3283 }
John Kessenichead86222018-03-28 18:01:20 -06003284 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003285 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003286 if (stride > 0)
3287 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003288 }
3289
3290 return spvType;
3291}
3292
John Kessenich0e737842017-03-24 18:38:16 -06003293// TODO: this functionality should exist at a higher level, in creating the AST
3294//
3295// Identify interface members that don't have their required extension turned on.
3296//
3297bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3298{
Chao Chen3c366992018-09-19 11:41:59 -07003299#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003300 auto& extensions = glslangIntermediate->getRequestedExtensions();
3301
Rex Xubcf291a2017-03-29 23:01:36 +08003302 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3303 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3304 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003305 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3306 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3307 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003308
3309 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3310 if (member.getFieldName() == "gl_ViewportMask" &&
3311 extensions.find("GL_NV_viewport_array2") == extensions.end())
3312 return true;
3313 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3314 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3315 return true;
3316 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3317 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3318 return true;
3319 }
3320#endif
John Kessenich0e737842017-03-24 18:38:16 -06003321
3322 return false;
3323};
3324
John Kessenich6090df02016-06-30 21:18:02 -06003325// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3326// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3327// Mutually recursive with convertGlslangToSpvType().
3328spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3329 const glslang::TTypeList* glslangMembers,
3330 glslang::TLayoutPacking explicitLayout,
3331 const glslang::TQualifier& qualifier)
3332{
3333 // Create a vector of struct types for SPIR-V to consume
3334 std::vector<spv::Id> spvMembers;
3335 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003336 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003337 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3338 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3339 if (glslangMember.hiddenMember()) {
3340 ++memberDelta;
3341 if (type.getBasicType() == glslang::EbtBlock)
3342 memberRemapper[glslangMembers][i] = -1;
3343 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003344 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003345 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003346 if (filterMember(glslangMember))
3347 continue;
3348 }
John Kessenich6090df02016-06-30 21:18:02 -06003349 // modify just this child's view of the qualifier
3350 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3351 InheritQualifiers(memberQualifier, qualifier);
3352
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003353 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003354 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003355 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003356
3357 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003358 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3359 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003360
3361 // Make forward pointers for any pointer members, and create a list of members to
3362 // convert to spirv types after creating the struct.
3363 if (glslangMember.getBasicType() == glslang::EbtReference) {
3364 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3365 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3366 }
3367 spvMembers.push_back(
3368 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3369 } else {
3370 spvMembers.push_back(
3371 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3372 }
John Kessenich6090df02016-06-30 21:18:02 -06003373 }
3374 }
3375
3376 // Make the SPIR-V type
3377 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003378 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003379 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3380
3381 // Decorate it
3382 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3383
John Kessenichd72f4882019-01-16 14:55:37 +07003384 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003385 auto it = deferredForwardPointers[i];
3386 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3387 }
3388
John Kessenich6090df02016-06-30 21:18:02 -06003389 return spvType;
3390}
3391
3392void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3393 const glslang::TTypeList* glslangMembers,
3394 glslang::TLayoutPacking explicitLayout,
3395 const glslang::TQualifier& qualifier,
3396 spv::Id spvType)
3397{
3398 // Name and decorate the non-hidden members
3399 int offset = -1;
3400 int locationOffset = 0; // for use within the members of this struct
3401 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3402 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3403 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003404 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003405 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003406 if (filterMember(glslangMember))
3407 continue;
3408 }
John Kessenich6090df02016-06-30 21:18:02 -06003409
3410 // modify just this child's view of the qualifier
3411 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3412 InheritQualifiers(memberQualifier, qualifier);
3413
3414 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003415 if (member < 0)
3416 continue;
3417
3418 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3419 builder.addMemberDecoration(spvType, member,
3420 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3421 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3422 // Add interpolation and auxiliary storage decorations only to
3423 // top-level members of Input and Output storage classes
3424 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3425 type.getQualifier().storage == glslang::EvqVaryingOut) {
3426 if (type.getBasicType() == glslang::EbtBlock ||
3427 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3428 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3429 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003430#ifdef NV_EXTENSIONS
3431 addMeshNVDecoration(spvType, member, memberQualifier);
3432#endif
John Kessenich6090df02016-06-30 21:18:02 -06003433 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003434 }
3435 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003436
John Kessenich5d610ee2018-03-07 18:05:55 -07003437 if (type.getBasicType() == glslang::EbtBlock &&
3438 qualifier.storage == glslang::EvqBuffer) {
3439 // Add memory decorations only to top-level members of shader storage block
3440 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003441 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003442 for (unsigned int i = 0; i < memory.size(); ++i)
3443 builder.addMemberDecoration(spvType, member, memory[i]);
3444 }
John Kessenich6090df02016-06-30 21:18:02 -06003445
John Kessenich5d610ee2018-03-07 18:05:55 -07003446 // Location assignment was already completed correctly by the front end,
3447 // just track whether a member needs to be decorated.
3448 // Ignore member locations if the container is an array, as that's
3449 // ill-specified and decisions have been made to not allow this.
3450 if (! type.isArray() && memberQualifier.hasLocation())
3451 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003452
John Kessenich5d610ee2018-03-07 18:05:55 -07003453 if (qualifier.hasLocation()) // track for upcoming inheritance
3454 locationOffset += glslangIntermediate->computeTypeLocationSize(
3455 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003456
John Kessenich5d610ee2018-03-07 18:05:55 -07003457 // component, XFB, others
3458 if (glslangMember.getQualifier().hasComponent())
3459 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3460 glslangMember.getQualifier().layoutComponent);
3461 if (glslangMember.getQualifier().hasXfbOffset())
3462 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3463 glslangMember.getQualifier().layoutXfbOffset);
3464 else if (explicitLayout != glslang::ElpNone) {
3465 // figure out what to do with offset, which is accumulating
3466 int nextOffset;
3467 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3468 if (offset >= 0)
3469 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3470 offset = nextOffset;
3471 }
John Kessenich6090df02016-06-30 21:18:02 -06003472
John Kessenich5d610ee2018-03-07 18:05:55 -07003473 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3474 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3475 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003476
John Kessenich5d610ee2018-03-07 18:05:55 -07003477 // built-in variable decorations
3478 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3479 if (builtIn != spv::BuiltInMax)
3480 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003481
John Kessenich5611c6d2018-04-05 11:25:02 -06003482 // nonuniform
3483 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3484
John Kessenichead86222018-03-28 18:01:20 -06003485 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3486 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3487 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3488 memberQualifier.semanticName);
3489 }
3490
chaoc771d89f2017-01-13 01:10:53 -08003491#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003492 if (builtIn == spv::BuiltInLayer) {
3493 // SPV_NV_viewport_array2 extension
3494 if (glslangMember.getQualifier().layoutViewportRelative){
3495 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3496 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3497 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003498 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003499 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3500 builder.addMemberDecoration(spvType, member,
3501 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3502 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3503 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3504 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003505 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003506 }
3507 if (glslangMember.getQualifier().layoutPassthrough) {
3508 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3509 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3510 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3511 }
chaoc771d89f2017-01-13 01:10:53 -08003512#endif
John Kessenich6090df02016-06-30 21:18:02 -06003513 }
3514
3515 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003516 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3517 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003518}
3519
John Kessenich6c292d32016-02-15 20:58:50 -07003520// Turn the expression forming the array size into an id.
3521// This is not quite trivial, because of specialization constants.
3522// Sometimes, a raw constant is turned into an Id, and sometimes
3523// a specialization constant expression is.
3524spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3525{
3526 // First, see if this is sized with a node, meaning a specialization constant:
3527 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3528 if (specNode != nullptr) {
3529 builder.clearAccessChain();
3530 specNode->traverse(this);
3531 return accessChainLoad(specNode->getAsTyped()->getType());
3532 }
qining25262b32016-05-06 17:25:16 -04003533
John Kessenich6c292d32016-02-15 20:58:50 -07003534 // Otherwise, need a compile-time (front end) size, get it:
3535 int size = arraySizes.getDimSize(dim);
3536 assert(size > 0);
3537 return builder.makeUintConstant(size);
3538}
3539
John Kessenich103bef92016-02-08 21:38:15 -07003540// Wrap the builder's accessChainLoad to:
3541// - localize handling of RelaxedPrecision
3542// - use the SPIR-V inferred type instead of another conversion of the glslang type
3543// (avoids unnecessary work and possible type punning for structures)
3544// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003545spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3546{
John Kessenich103bef92016-02-08 21:38:15 -07003547 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003548
3549 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3550 coherentFlags |= TranslateCoherent(type);
3551
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003552 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003553 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003554
John Kessenich5611c6d2018-04-05 11:25:02 -06003555 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003556 TranslateNonUniformDecoration(type.getQualifier()),
3557 nominalTypeId,
3558 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003559 TranslateMemoryScope(coherentFlags),
3560 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003561
3562 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003563 if (type.getBasicType() == glslang::EbtBool) {
3564 if (builder.isScalarType(nominalTypeId)) {
3565 // Conversion for bool
3566 spv::Id boolType = builder.makeBoolType();
3567 if (nominalTypeId != boolType)
3568 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3569 } else if (builder.isVectorType(nominalTypeId)) {
3570 // Conversion for bvec
3571 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3572 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3573 if (nominalTypeId != bvecType)
3574 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3575 }
3576 }
John Kessenich103bef92016-02-08 21:38:15 -07003577
3578 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003579}
3580
Rex Xu27253232016-02-23 17:51:09 +08003581// Wrap the builder's accessChainStore to:
3582// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003583//
3584// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003585void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3586{
3587 // Need to convert to abstract types when necessary
3588 if (type.getBasicType() == glslang::EbtBool) {
3589 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3590
3591 if (builder.isScalarType(nominalTypeId)) {
3592 // Conversion for bool
3593 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003594 if (nominalTypeId != boolType) {
3595 // keep these outside arguments, for determinant order-of-evaluation
3596 spv::Id one = builder.makeUintConstant(1);
3597 spv::Id zero = builder.makeUintConstant(0);
3598 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3599 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003600 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003601 } else if (builder.isVectorType(nominalTypeId)) {
3602 // Conversion for bvec
3603 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3604 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003605 if (nominalTypeId != bvecType) {
3606 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003607 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3608 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3609 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003610 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003611 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3612 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003613 }
3614 }
3615
Jeff Bolz36831c92018-09-05 10:11:41 -05003616 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3617 coherentFlags |= TranslateCoherent(type);
3618
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003619 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003620 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003621
Jeff Bolz36831c92018-09-05 10:11:41 -05003622 builder.accessChainStore(rvalue,
3623 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003625}
3626
John Kessenich4bf71552016-09-02 11:20:21 -06003627// For storing when types match at the glslang level, but not might match at the
3628// SPIR-V level.
3629//
3630// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003631// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003632// as in a member-decorated way.
3633//
3634// NOTE: This function can handle any store request; if it's not special it
3635// simplifies to a simple OpStore.
3636//
3637// Implicitly uses the existing builder.accessChain as the storage target.
3638void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3639{
John Kessenichb3e24e42016-09-11 12:33:43 -06003640 // we only do the complex path here if it's an aggregate
3641 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003642 accessChainStore(type, rValue);
3643 return;
3644 }
3645
John Kessenichb3e24e42016-09-11 12:33:43 -06003646 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003647 spv::Id rType = builder.getTypeId(rValue);
3648 spv::Id lValue = builder.accessChainGetLValue();
3649 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3650 if (lType == rType) {
3651 accessChainStore(type, rValue);
3652 return;
3653 }
3654
John Kessenichb3e24e42016-09-11 12:33:43 -06003655 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003656 // where the two types were the same type in GLSL. This requires member
3657 // by member copy, recursively.
3658
John Kessenichb3e24e42016-09-11 12:33:43 -06003659 // If an array, copy element by element.
3660 if (type.isArray()) {
3661 glslang::TType glslangElementType(type, 0);
3662 spv::Id elementRType = builder.getContainedTypeId(rType);
3663 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3664 // get the source member
3665 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003666
John Kessenichb3e24e42016-09-11 12:33:43 -06003667 // set up the target storage
3668 builder.clearAccessChain();
3669 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003670 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003671
John Kessenichb3e24e42016-09-11 12:33:43 -06003672 // store the member
3673 multiTypeStore(glslangElementType, elementRValue);
3674 }
3675 } else {
3676 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003677
John Kessenichb3e24e42016-09-11 12:33:43 -06003678 // loop over structure members
3679 const glslang::TTypeList& members = *type.getStruct();
3680 for (int m = 0; m < (int)members.size(); ++m) {
3681 const glslang::TType& glslangMemberType = *members[m].type;
3682
3683 // get the source member
3684 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3685 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3686
3687 // set up the target storage
3688 builder.clearAccessChain();
3689 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003690 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003691
3692 // store the member
3693 multiTypeStore(glslangMemberType, memberRValue);
3694 }
John Kessenich4bf71552016-09-02 11:20:21 -06003695 }
3696}
3697
John Kessenichf85e8062015-12-19 13:57:10 -07003698// Decide whether or not this type should be
3699// decorated with offsets and strides, and if so
3700// whether std140 or std430 rules should be applied.
3701glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003702{
John Kessenichf85e8062015-12-19 13:57:10 -07003703 // has to be a block
3704 if (type.getBasicType() != glslang::EbtBlock)
3705 return glslang::ElpNone;
3706
Chao Chen3c366992018-09-19 11:41:59 -07003707 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003708 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003709 type.getQualifier().storage != glslang::EvqBuffer &&
3710 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003711 return glslang::ElpNone;
3712
3713 // return the layout to use
3714 switch (type.getQualifier().layoutPacking) {
3715 case glslang::ElpStd140:
3716 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003717 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003718 return type.getQualifier().layoutPacking;
3719 default:
3720 return glslang::ElpNone;
3721 }
John Kessenich31ed4832015-09-09 17:51:38 -06003722}
3723
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003724// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003725int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003726{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003727 int size;
John Kessenich49987892015-12-29 17:11:44 -07003728 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003729 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003730
3731 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003732}
3733
John Kessenich49987892015-12-29 17:11:44 -07003734// 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 -07003735// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003736int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003737{
John Kessenich49987892015-12-29 17:11:44 -07003738 glslang::TType elementType;
3739 elementType.shallowCopy(matrixType);
3740 elementType.clearArraySizes();
3741
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003742 int size;
John Kessenich49987892015-12-29 17:11:44 -07003743 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003744 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003745
3746 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003747}
3748
John Kessenich5e4b1242015-08-06 22:53:06 -06003749// Given a member type of a struct, realign the current offset for it, and compute
3750// the next (not yet aligned) offset for the next member, which will get aligned
3751// on the next call.
3752// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3753// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3754// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003755void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003756 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003757{
3758 // this will get a positive value when deemed necessary
3759 nextOffset = -1;
3760
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 // override anything in currentOffset with user-set offset
3762 if (memberType.getQualifier().hasOffset())
3763 currentOffset = memberType.getQualifier().layoutOffset;
3764
3765 // It could be that current linker usage in glslang updated all the layoutOffset,
3766 // in which case the following code does not matter. But, that's not quite right
3767 // once cross-compilation unit GLSL validation is done, as the original user
3768 // settings are needed in layoutOffset, and then the following will come into play.
3769
John Kessenichf85e8062015-12-19 13:57:10 -07003770 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 if (! memberType.getQualifier().hasOffset())
3772 currentOffset = -1;
3773
3774 return;
3775 }
3776
John Kessenichf85e8062015-12-19 13:57:10 -07003777 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003778 if (currentOffset < 0)
3779 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003780
John Kessenich5e4b1242015-08-06 22:53:06 -06003781 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3782 // but possibly not yet correctly aligned.
3783
3784 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003785 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003786 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003787
3788 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003789 // TODO: make this consistent in early phases of code:
3790 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3791 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3792 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003793 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003794 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003795 int dummySize;
3796 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3797 if (componentAlignment <= 4)
3798 memberAlignment = componentAlignment;
3799 }
3800
3801 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003803
3804 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003805 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003806 glslang::RoundToPow2(currentOffset, 16);
3807
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 nextOffset = currentOffset + memberSize;
3809}
3810
David Netoa901ffe2016-06-08 14:11:40 +01003811void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003812{
David Netoa901ffe2016-06-08 14:11:40 +01003813 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3814 switch (glslangBuiltIn)
3815 {
3816 case glslang::EbvClipDistance:
3817 case glslang::EbvCullDistance:
3818 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003819#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003820 case glslang::EbvViewportMaskNV:
3821 case glslang::EbvSecondaryPositionNV:
3822 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003823 case glslang::EbvPositionPerViewNV:
3824 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003825 case glslang::EbvTaskCountNV:
3826 case glslang::EbvPrimitiveCountNV:
3827 case glslang::EbvPrimitiveIndicesNV:
3828 case glslang::EbvClipDistancePerViewNV:
3829 case glslang::EbvCullDistancePerViewNV:
3830 case glslang::EbvLayerPerViewNV:
3831 case glslang::EbvMeshViewCountNV:
3832 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003833#endif
David Netoa901ffe2016-06-08 14:11:40 +01003834 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3835 // Alternately, we could just call this for any glslang built-in, since the
3836 // capability already guards against duplicates.
3837 TranslateBuiltInDecoration(glslangBuiltIn, false);
3838 break;
3839 default:
3840 // Capabilities were already generated when the struct was declared.
3841 break;
3842 }
John Kessenichebb50532016-05-16 19:22:05 -06003843}
3844
John Kessenich6fccb3c2016-09-19 16:01:41 -06003845bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003846{
John Kessenicheee9d532016-09-19 18:09:30 -06003847 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003848}
3849
John Kessenichd41993d2017-09-10 15:21:05 -06003850// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003851// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3852// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003853bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003854{
John Kessenich6a14f782017-12-04 02:48:10 -07003855 assert(qualifier == glslang::EvqIn ||
3856 qualifier == glslang::EvqOut ||
3857 qualifier == glslang::EvqInOut ||
3858 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003859 return qualifier != glslang::EvqConstReadOnly;
3860}
3861
3862// Is parameter pass-by-original?
3863bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3864 bool implicitThisParam)
3865{
3866 if (implicitThisParam) // implicit this
3867 return true;
3868 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003869 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003870 return paramType.containsOpaque() || // sampler, etc.
3871 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3872}
3873
John Kessenich140f3df2015-06-26 16:58:36 -06003874// Make all the functions, skeletally, without actually visiting their bodies.
3875void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3876{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003877 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003878 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3879 if (paramPrecision != spv::NoPrecision)
3880 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003881 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003882 if (type.getBasicType() == glslang::EbtReference) {
3883 // Original and non-writable params pass the pointer directly and
3884 // use restrict/aliased, others are stored to a pointer in Function
3885 // memory and use RestrictPointer/AliasedPointer.
3886 if (originalParam(type.getQualifier().storage, type, false) ||
3887 !writableParam(type.getQualifier().storage)) {
3888 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3889 } else {
3890 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3891 }
3892 }
John Kessenichfad62972017-07-18 02:35:46 -06003893 };
3894
John Kessenich140f3df2015-06-26 16:58:36 -06003895 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3896 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003897 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003898 continue;
3899
3900 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003901 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003902 //
qining25262b32016-05-06 17:25:16 -04003903 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003904 // function. What it is an address of varies:
3905 //
John Kessenich4bf71552016-09-02 11:20:21 -06003906 // - "in" parameters not marked as "const" can be written to without modifying the calling
3907 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003908 //
3909 // - "const in" parameters can just be the r-value, as no writes need occur.
3910 //
John Kessenich4bf71552016-09-02 11:20:21 -06003911 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3912 // 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 -06003913
3914 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003915 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003916 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3917
John Kessenichfad62972017-07-18 02:35:46 -06003918 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3919 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003920
John Kessenichfad62972017-07-18 02:35:46 -06003921 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003922 for (int p = 0; p < (int)parameters.size(); ++p) {
3923 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3924 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003925 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003926 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003927 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003928 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3929 else
John Kessenich4bf71552016-09-02 11:20:21 -06003930 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003931 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003932 paramTypes.push_back(typeId);
3933 }
3934
3935 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003936 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3937 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003938 glslFunction->getName().c_str(), paramTypes,
3939 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003940 if (implicitThis)
3941 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003942
3943 // Track function to emit/call later
3944 functionMap[glslFunction->getName().c_str()] = function;
3945
3946 // Set the parameter id's
3947 for (int p = 0; p < (int)parameters.size(); ++p) {
3948 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3949 // give a name too
3950 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3951 }
3952 }
3953}
3954
3955// Process all the initializers, while skipping the functions and link objects
3956void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3957{
3958 builder.setBuildPoint(shaderEntry->getLastBlock());
3959 for (int i = 0; i < (int)initializers.size(); ++i) {
3960 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3961 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3962
3963 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003964 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003965 initializer->traverse(this);
3966 }
3967 }
3968}
3969
3970// Process all the functions, while skipping initializers.
3971void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3972{
3973 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3974 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003975 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003976 node->traverse(this);
3977 }
3978}
3979
3980void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3981{
qining25262b32016-05-06 17:25:16 -04003982 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003983 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003984 currentFunction = functionMap[node->getName().c_str()];
3985 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003986 builder.setBuildPoint(functionBlock);
3987}
3988
Rex Xu04db3f52015-09-16 11:44:02 +08003989void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003990{
Rex Xufc618912015-09-09 16:42:49 +08003991 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003992
3993 glslang::TSampler sampler = {};
3994 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003995#ifdef AMD_EXTENSIONS
3996 bool f16ShadowCompare = false;
3997#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003998 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003999 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4000 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004001#ifdef AMD_EXTENSIONS
4002 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4003#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004004 }
4005
John Kessenich140f3df2015-06-26 16:58:36 -06004006 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4007 builder.clearAccessChain();
4008 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004009
4010 // Special case l-value operands
4011 bool lvalue = false;
4012 switch (node.getOp()) {
4013 case glslang::EOpImageAtomicAdd:
4014 case glslang::EOpImageAtomicMin:
4015 case glslang::EOpImageAtomicMax:
4016 case glslang::EOpImageAtomicAnd:
4017 case glslang::EOpImageAtomicOr:
4018 case glslang::EOpImageAtomicXor:
4019 case glslang::EOpImageAtomicExchange:
4020 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004021 case glslang::EOpImageAtomicLoad:
4022 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004023 if (i == 0)
4024 lvalue = true;
4025 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004026 case glslang::EOpSparseImageLoad:
4027 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4028 lvalue = true;
4029 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004030#ifdef AMD_EXTENSIONS
4031 case glslang::EOpSparseTexture:
4032 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4033 lvalue = true;
4034 break;
4035 case glslang::EOpSparseTextureClamp:
4036 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4037 lvalue = true;
4038 break;
4039 case glslang::EOpSparseTextureLod:
4040 case glslang::EOpSparseTextureOffset:
4041 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4042 lvalue = true;
4043 break;
4044#else
Rex Xu48edadf2015-12-31 16:11:41 +08004045 case glslang::EOpSparseTexture:
4046 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4047 lvalue = true;
4048 break;
4049 case glslang::EOpSparseTextureClamp:
4050 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4051 lvalue = true;
4052 break;
4053 case glslang::EOpSparseTextureLod:
4054 case glslang::EOpSparseTextureOffset:
4055 if (i == 3)
4056 lvalue = true;
4057 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004058#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004059 case glslang::EOpSparseTextureFetch:
4060 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4061 lvalue = true;
4062 break;
4063 case glslang::EOpSparseTextureFetchOffset:
4064 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4065 lvalue = true;
4066 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004067#ifdef AMD_EXTENSIONS
4068 case glslang::EOpSparseTextureLodOffset:
4069 case glslang::EOpSparseTextureGrad:
4070 case glslang::EOpSparseTextureOffsetClamp:
4071 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4072 lvalue = true;
4073 break;
4074 case glslang::EOpSparseTextureGradOffset:
4075 case glslang::EOpSparseTextureGradClamp:
4076 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4077 lvalue = true;
4078 break;
4079 case glslang::EOpSparseTextureGradOffsetClamp:
4080 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4081 lvalue = true;
4082 break;
4083#else
Rex Xu48edadf2015-12-31 16:11:41 +08004084 case glslang::EOpSparseTextureLodOffset:
4085 case glslang::EOpSparseTextureGrad:
4086 case glslang::EOpSparseTextureOffsetClamp:
4087 if (i == 4)
4088 lvalue = true;
4089 break;
4090 case glslang::EOpSparseTextureGradOffset:
4091 case glslang::EOpSparseTextureGradClamp:
4092 if (i == 5)
4093 lvalue = true;
4094 break;
4095 case glslang::EOpSparseTextureGradOffsetClamp:
4096 if (i == 6)
4097 lvalue = true;
4098 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004099#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004100 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004101 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4102 lvalue = true;
4103 break;
4104 case glslang::EOpSparseTextureGatherOffset:
4105 case glslang::EOpSparseTextureGatherOffsets:
4106 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4107 lvalue = true;
4108 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004109#ifdef AMD_EXTENSIONS
4110 case glslang::EOpSparseTextureGatherLod:
4111 if (i == 3)
4112 lvalue = true;
4113 break;
4114 case glslang::EOpSparseTextureGatherLodOffset:
4115 case glslang::EOpSparseTextureGatherLodOffsets:
4116 if (i == 4)
4117 lvalue = true;
4118 break;
Rex Xu129799a2017-07-05 17:23:28 +08004119 case glslang::EOpSparseImageLoadLod:
4120 if (i == 3)
4121 lvalue = true;
4122 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004123#endif
Chao Chen3a137962018-09-19 11:41:27 -07004124#ifdef NV_EXTENSIONS
4125 case glslang::EOpImageSampleFootprintNV:
4126 if (i == 4)
4127 lvalue = true;
4128 break;
4129 case glslang::EOpImageSampleFootprintClampNV:
4130 case glslang::EOpImageSampleFootprintLodNV:
4131 if (i == 5)
4132 lvalue = true;
4133 break;
4134 case glslang::EOpImageSampleFootprintGradNV:
4135 if (i == 6)
4136 lvalue = true;
4137 break;
4138 case glslang::EOpImageSampleFootprintGradClampNV:
4139 if (i == 7)
4140 lvalue = true;
4141 break;
4142#endif
Rex Xufc618912015-09-09 16:42:49 +08004143 default:
4144 break;
4145 }
4146
Rex Xu6b86d492015-09-16 17:48:22 +08004147 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004148 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004149 else
John Kessenich32cfd492016-02-02 12:37:46 -07004150 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004151 }
4152}
4153
John Kessenichfc51d282015-08-19 13:34:18 -06004154void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004155{
John Kessenichfc51d282015-08-19 13:34:18 -06004156 builder.clearAccessChain();
4157 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004158 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004159}
John Kessenich140f3df2015-06-26 16:58:36 -06004160
John Kessenichfc51d282015-08-19 13:34:18 -06004161spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4162{
John Kesseniche485c7a2017-05-31 18:50:53 -06004163 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004164 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004165
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004166 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004167
John Kessenichfc51d282015-08-19 13:34:18 -06004168 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004169
4170 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4171 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4172 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004173#ifdef AMD_EXTENSIONS
4174 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4175 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4176 : false;
4177#endif
4178
John Kessenichfc51d282015-08-19 13:34:18 -06004179 std::vector<spv::Id> arguments;
4180 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004181 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004182 else
4183 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004184 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004185
4186 spv::Builder::TextureParameters params = { };
4187 params.sampler = arguments[0];
4188
Rex Xu04db3f52015-09-16 11:44:02 +08004189 glslang::TCrackedTextureOp cracked;
4190 node->crackTexture(sampler, cracked);
4191
amhagan05506bb2017-06-13 16:53:02 -04004192 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004193
John Kessenichfc51d282015-08-19 13:34:18 -06004194 // Check for queries
4195 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004196 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4197 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004198 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004199
John Kessenichfc51d282015-08-19 13:34:18 -06004200 switch (node->getOp()) {
4201 case glslang::EOpImageQuerySize:
4202 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004203 if (arguments.size() > 1) {
4204 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004205 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004206 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004207 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004208 case glslang::EOpImageQuerySamples:
4209 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004210 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004211 case glslang::EOpTextureQueryLod:
4212 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004213 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004214 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004215 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004216 case glslang::EOpSparseTexelsResident:
4217 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004218 default:
4219 assert(0);
4220 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004221 }
John Kessenich140f3df2015-06-26 16:58:36 -06004222 }
4223
LoopDawg4425f242018-02-18 11:40:01 -07004224 int components = node->getType().getVectorSize();
4225
4226 if (node->getOp() == glslang::EOpTextureFetch) {
4227 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4228 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4229 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4230 // here around e.g. which ones return scalars or other types.
4231 components = 4;
4232 }
4233
4234 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4235
4236 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4237
Rex Xufc618912015-09-09 16:42:49 +08004238 // Check for image functions other than queries
4239 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004240 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004241 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004242 spv::IdImmediate image = { true, *(opIt++) };
4243 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004244
4245 // Handle subpass operations
4246 // TODO: GLSL should change to have the "MS" only on the type rather than the
4247 // built-in function.
4248 if (cracked.subpass) {
4249 // add on the (0,0) coordinate
4250 spv::Id zero = builder.makeIntConstant(0);
4251 std::vector<spv::Id> comps;
4252 comps.push_back(zero);
4253 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004254 spv::IdImmediate coord = { true,
4255 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4256 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004257 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004258 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4259 operands.push_back(imageOperands);
4260 spv::IdImmediate imageOperand = { true, *(opIt++) };
4261 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004262 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004263 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4264 builder.setPrecision(result, precision);
4265 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004266 }
4267
John Kessenich149afc32018-08-14 13:31:43 -06004268 spv::IdImmediate coord = { true, *(opIt++) };
4269 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004270#ifdef AMD_EXTENSIONS
4271 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4272#else
John Kessenich56bab042015-09-16 10:54:31 -06004273 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004274#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004275 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004276 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004277 mask = mask | spv::ImageOperandsSampleMask;
4278 }
Rex Xu129799a2017-07-05 17:23:28 +08004279#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004280 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004281 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4282 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004283 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004284 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004285#endif
4286 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4287 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4288 if (mask) {
4289 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4290 operands.push_back(imageOperands);
4291 }
4292 if (mask & spv::ImageOperandsSampleMask) {
4293 spv::IdImmediate imageOperand = { true, *opIt++ };
4294 operands.push_back(imageOperand);
4295 }
4296#ifdef AMD_EXTENSIONS
4297 if (mask & spv::ImageOperandsLodMask) {
4298 spv::IdImmediate imageOperand = { true, *opIt++ };
4299 operands.push_back(imageOperand);
4300 }
4301#endif
4302 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4303 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4304 operands.push_back(imageOperand);
4305 }
4306
John Kessenich149afc32018-08-14 13:31:43 -06004307 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004308 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004309
John Kessenich149afc32018-08-14 13:31:43 -06004310 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004311 builder.setPrecision(result[0], precision);
4312
4313 // If needed, add a conversion constructor to the proper size.
4314 if (components != node->getType().getVectorSize())
4315 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4316
4317 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004318#ifdef AMD_EXTENSIONS
4319 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4320#else
John Kessenich56bab042015-09-16 10:54:31 -06004321 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004322#endif
Rex Xu129799a2017-07-05 17:23:28 +08004323
Jeff Bolz36831c92018-09-05 10:11:41 -05004324 // Push the texel value before the operands
4325#ifdef AMD_EXTENSIONS
4326 if (sampler.ms || cracked.lod) {
4327#else
4328 if (sampler.ms) {
4329#endif
John Kessenich149afc32018-08-14 13:31:43 -06004330 spv::IdImmediate texel = { true, *(opIt + 1) };
4331 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004332 } else {
4333 spv::IdImmediate texel = { true, *opIt };
4334 operands.push_back(texel);
4335 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004336
4337 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4338 if (sampler.ms) {
4339 mask = mask | spv::ImageOperandsSampleMask;
4340 }
4341#ifdef AMD_EXTENSIONS
4342 if (cracked.lod) {
4343 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4344 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4345 mask = mask | spv::ImageOperandsLodMask;
4346 }
4347#endif
4348 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4349 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4350 if (mask) {
4351 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4352 operands.push_back(imageOperands);
4353 }
4354 if (mask & spv::ImageOperandsSampleMask) {
4355 spv::IdImmediate imageOperand = { true, *opIt++ };
4356 operands.push_back(imageOperand);
4357 }
4358#ifdef AMD_EXTENSIONS
4359 if (mask & spv::ImageOperandsLodMask) {
4360 spv::IdImmediate imageOperand = { true, *opIt++ };
4361 operands.push_back(imageOperand);
4362 }
4363#endif
4364 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4365 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4366 operands.push_back(imageOperand);
4367 }
4368
John Kessenich56bab042015-09-16 10:54:31 -06004369 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004370 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004371 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004372 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004373#ifdef AMD_EXTENSIONS
4374 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4375#else
Rex Xu5eafa472016-02-19 22:24:03 +08004376 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004377#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004378 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004379 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004380 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4381
Jeff Bolz36831c92018-09-05 10:11:41 -05004382 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004383 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004384 mask = mask | spv::ImageOperandsSampleMask;
4385 }
Rex Xu129799a2017-07-05 17:23:28 +08004386#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004387 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004388 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4389 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4390
Jeff Bolz36831c92018-09-05 10:11:41 -05004391 mask = mask | spv::ImageOperandsLodMask;
4392 }
4393#endif
4394 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4395 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4396 if (mask) {
4397 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004398 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004399 }
4400 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004401 spv::IdImmediate imageOperand = { true, *opIt++ };
4402 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004403 }
4404#ifdef AMD_EXTENSIONS
4405 if (mask & spv::ImageOperandsLodMask) {
4406 spv::IdImmediate imageOperand = { true, *opIt++ };
4407 operands.push_back(imageOperand);
4408 }
Rex Xu129799a2017-07-05 17:23:28 +08004409#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004410 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4411 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4412 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004413 }
4414
4415 // Create the return type that was a special structure
4416 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004417 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004418 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4419 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4420
4421 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4422
4423 // Decode the return type
4424 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4425 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004426 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004427 // Process image atomic operations
4428
4429 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4430 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004431 // For non-MS, the sample value should be 0
4432 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4433 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004434
Jeff Bolz36831c92018-09-05 10:11:41 -05004435 spv::Id resultTypeId;
4436 // imageAtomicStore has a void return type so base the pointer type on
4437 // the type of the value operand.
4438 if (node->getOp() == glslang::EOpImageAtomicStore) {
4439 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4440 } else {
4441 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4442 }
John Kessenich56bab042015-09-16 10:54:31 -06004443 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004444
4445 std::vector<spv::Id> operands;
4446 operands.push_back(pointer);
4447 for (; opIt != arguments.end(); ++opIt)
4448 operands.push_back(*opIt);
4449
John Kessenich8c8505c2016-07-26 12:50:38 -06004450 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004451 }
4452 }
4453
amhagan05506bb2017-06-13 16:53:02 -04004454#ifdef AMD_EXTENSIONS
4455 // Check for fragment mask functions other than queries
4456 if (cracked.fragMask) {
4457 assert(sampler.ms);
4458
4459 auto opIt = arguments.begin();
4460 std::vector<spv::Id> operands;
4461
4462 // Extract the image if necessary
4463 if (builder.isSampledImage(params.sampler))
4464 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4465
4466 operands.push_back(params.sampler);
4467 ++opIt;
4468
4469 if (sampler.isSubpass()) {
4470 // add on the (0,0) coordinate
4471 spv::Id zero = builder.makeIntConstant(0);
4472 std::vector<spv::Id> comps;
4473 comps.push_back(zero);
4474 comps.push_back(zero);
4475 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4476 }
4477
4478 for (; opIt != arguments.end(); ++opIt)
4479 operands.push_back(*opIt);
4480
4481 spv::Op fragMaskOp = spv::OpNop;
4482 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4483 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4484 else if (node->getOp() == glslang::EOpFragmentFetch)
4485 fragMaskOp = spv::OpFragmentFetchAMD;
4486
4487 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4488 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4489 return builder.createOp(fragMaskOp, resultType(), operands);
4490 }
4491#endif
4492
Rex Xufc618912015-09-09 16:42:49 +08004493 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004494 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004495#ifdef NV_EXTENSIONS
4496 bool imageFootprint = node->isImageFootprint();
4497#endif
4498
Rex Xu71519fe2015-11-11 15:35:47 +08004499 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4500
John Kessenichfc51d282015-08-19 13:34:18 -06004501 // check for bias argument
4502 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004503#ifdef AMD_EXTENSIONS
4504 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4505#else
Rex Xu71519fe2015-11-11 15:35:47 +08004506 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004507#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004508 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004509#ifdef AMD_EXTENSIONS
4510 if (cracked.gather)
4511 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004512
4513 if (f16ShadowCompare)
4514 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004515#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004516 if (cracked.offset)
4517 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004518#ifdef AMD_EXTENSIONS
4519 else if (cracked.offsets)
4520 ++nonBiasArgCount;
4521#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004522 if (cracked.grad)
4523 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004524 if (cracked.lodClamp)
4525 ++nonBiasArgCount;
4526 if (sparse)
4527 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004528#ifdef NV_EXTENSIONS
4529 if (imageFootprint)
4530 //Following three extra arguments
4531 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4532 nonBiasArgCount += 3;
4533#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004534 if ((int)arguments.size() > nonBiasArgCount)
4535 bias = true;
4536 }
4537
John Kessenicha5c33d62016-06-02 23:45:21 -06004538 // See if the sampler param should really be just the SPV image part
4539 if (cracked.fetch) {
4540 // a fetch needs to have the image extracted first
4541 if (builder.isSampledImage(params.sampler))
4542 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4543 }
4544
Rex Xu225e0fc2016-11-17 17:47:59 +08004545#ifdef AMD_EXTENSIONS
4546 if (cracked.gather) {
4547 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4548 if (bias || cracked.lod ||
4549 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4550 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004551 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004552 }
4553 }
4554#endif
4555
John Kessenichfc51d282015-08-19 13:34:18 -06004556 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004557
John Kessenichfc51d282015-08-19 13:34:18 -06004558 params.coords = arguments[1];
4559 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004560 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004561
4562 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004563#ifdef AMD_EXTENSIONS
4564 if (cubeCompare || f16ShadowCompare) {
4565#else
Rex Xu48edadf2015-12-31 16:11:41 +08004566 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004567#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004568 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004569 ++extraArgs;
4570 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004571 params.Dref = arguments[2];
4572 ++extraArgs;
4573 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004574 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004575 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004576 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004577 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004578 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004579 dRefComp = builder.getNumComponents(params.coords) - 1;
4580 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004581 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4582 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004583
4584 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004585 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004586 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004587 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004588 } else if (glslangIntermediate->getStage() != EShLangFragment
4589#ifdef NV_EXTENSIONS
4590 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4591 && !(glslangIntermediate->getStage() == EShLangCompute &&
4592 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4593#endif
4594 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004595 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4596 noImplicitLod = true;
4597 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004598
4599 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004600 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004601 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004602 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004603 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004604
4605 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004606 if (cracked.grad) {
4607 params.gradX = arguments[2 + extraArgs];
4608 params.gradY = arguments[3 + extraArgs];
4609 extraArgs += 2;
4610 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004611
4612 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004613 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004614 params.offset = arguments[2 + extraArgs];
4615 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004616 } else if (cracked.offsets) {
4617 params.offsets = arguments[2 + extraArgs];
4618 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004619 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004620
4621 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004622 if (cracked.lodClamp) {
4623 params.lodClamp = arguments[2 + extraArgs];
4624 ++extraArgs;
4625 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004626 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004627 if (sparse) {
4628 params.texelOut = arguments[2 + extraArgs];
4629 ++extraArgs;
4630 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004631
John Kessenich76d4dfc2016-06-16 12:43:23 -06004632 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004633 if (cracked.gather && ! sampler.shadow) {
4634 // default component is 0, if missing, otherwise an argument
4635 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004636 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004637 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004638 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004639 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004640 }
Chao Chen3a137962018-09-19 11:41:27 -07004641#ifdef NV_EXTENSIONS
4642 spv::Id resultStruct = spv::NoResult;
4643 if (imageFootprint) {
4644 //Following three extra arguments
4645 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4646 params.granularity = arguments[2 + extraArgs];
4647 params.coarse = arguments[3 + extraArgs];
4648 resultStruct = arguments[4 + extraArgs];
4649 extraArgs += 3;
4650 }
4651#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004652 // bias
4653 if (bias) {
4654 params.bias = arguments[2 + extraArgs];
4655 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004656 }
John Kessenichfc51d282015-08-19 13:34:18 -06004657
Chao Chen3a137962018-09-19 11:41:27 -07004658#ifdef NV_EXTENSIONS
4659 if (imageFootprint) {
4660 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4661 builder.addCapability(spv::CapabilityImageFootprintNV);
4662
4663
4664 //resultStructType(OpenGL type) contains 5 elements:
4665 //struct gl_TextureFootprint2DNV {
4666 // uvec2 anchor;
4667 // uvec2 offset;
4668 // uvec2 mask;
4669 // uint lod;
4670 // uint granularity;
4671 //};
4672 //or
4673 //struct gl_TextureFootprint3DNV {
4674 // uvec3 anchor;
4675 // uvec3 offset;
4676 // uvec2 mask;
4677 // uint lod;
4678 // uint granularity;
4679 //};
4680 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4681 assert(builder.isStructType(resultStructType));
4682
4683 //resType (SPIR-V type) contains 6 elements:
4684 //Member 0 must be a Boolean type scalar(LOD),
4685 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4686 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4687 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4688 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4689 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4690 std::vector<spv::Id> members;
4691 members.push_back(resultType());
4692 for (int i = 0; i < 5; i++) {
4693 members.push_back(builder.getContainedTypeId(resultStructType, i));
4694 }
4695 spv::Id resType = builder.makeStructType(members, "ResType");
4696
4697 //call ImageFootprintNV
4698 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4699
4700 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4701 for (int i = 0; i < 5; i++) {
4702 builder.clearAccessChain();
4703 builder.setAccessChainLValue(resultStruct);
4704
4705 //Accessing to a struct we created, no coherent flag is set
4706 spv::Builder::AccessChain::CoherentFlags flags;
4707 flags.clear();
4708
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004709 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004710 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4711 }
4712 return builder.createCompositeExtract(res, resultType(), 0);
4713 }
4714#endif
4715
John Kessenich65336482016-06-16 14:06:26 -06004716 // projective component (might not to move)
4717 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4718 // are divided by the last component of P."
4719 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4720 // unused components will appear after all used components."
4721 if (cracked.proj) {
4722 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4723 int projTargetComp;
4724 switch (sampler.dim) {
4725 case glslang::Esd1D: projTargetComp = 1; break;
4726 case glslang::Esd2D: projTargetComp = 2; break;
4727 case glslang::EsdRect: projTargetComp = 2; break;
4728 default: projTargetComp = projSourceComp; break;
4729 }
4730 // copy the projective coordinate if we have to
4731 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004732 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004733 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4734 projSourceComp);
4735 params.coords = builder.createCompositeInsert(projComp, params.coords,
4736 builder.getTypeId(params.coords), projTargetComp);
4737 }
4738 }
4739
Jeff Bolz36831c92018-09-05 10:11:41 -05004740 // nonprivate
4741 if (imageType.getQualifier().nonprivate) {
4742 params.nonprivate = true;
4743 }
4744
4745 // volatile
4746 if (imageType.getQualifier().volatil) {
4747 params.volatil = true;
4748 }
4749
St0fFa1184dd2018-04-09 21:08:14 +02004750 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004751 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004752 );
LoopDawg4425f242018-02-18 11:40:01 -07004753
4754 if (components != node->getType().getVectorSize())
4755 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4756
4757 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004758}
4759
4760spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4761{
4762 // Grab the function's pointer from the previously created function
4763 spv::Function* function = functionMap[node->getName().c_str()];
4764 if (! function)
4765 return 0;
4766
4767 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4768 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4769
4770 // See comments in makeFunctions() for details about the semantics for parameter passing.
4771 //
4772 // These imply we need a four step process:
4773 // 1. Evaluate the arguments
4774 // 2. Allocate and make copies of in, out, and inout arguments
4775 // 3. Make the call
4776 // 4. Copy back the results
4777
John Kessenichd3ed90b2018-05-04 11:43:03 -06004778 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004779 std::vector<spv::Builder::AccessChain> lValues;
4780 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004781 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004782 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004783 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004784 // build l-value
4785 builder.clearAccessChain();
4786 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004787 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004788 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004789 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004790 // save l-value
4791 lValues.push_back(builder.getAccessChain());
4792 } else {
4793 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004794 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004795 }
4796 }
4797
4798 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4799 // copy the original into that space.
4800 //
4801 // Also, build up the list of actual arguments to pass in for the call
4802 int lValueCount = 0;
4803 int rValueCount = 0;
4804 std::vector<spv::Id> spvArgs;
4805 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4806 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004807 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004808 builder.setAccessChain(lValues[lValueCount]);
4809 arg = builder.accessChainGetLValue();
4810 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004811 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004812 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004813 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004814 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4815 // need to copy the input into output space
4816 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004817 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004818 builder.clearAccessChain();
4819 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004820 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004821 }
4822 ++lValueCount;
4823 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004824 // process r-value, which involves a copy for a type mismatch
4825 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4826 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4827 builder.clearAccessChain();
4828 builder.setAccessChainLValue(argCopy);
4829 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4830 arg = builder.createLoad(argCopy);
4831 } else
4832 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004833 ++rValueCount;
4834 }
4835 spvArgs.push_back(arg);
4836 }
4837
4838 // 3. Make the call.
4839 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004840 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004841
4842 // 4. Copy back out an "out" arguments.
4843 lValueCount = 0;
4844 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004845 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004846 ++lValueCount;
4847 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004848 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4849 spv::Id copy = builder.createLoad(spvArgs[a]);
4850 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004851 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004852 }
4853 ++lValueCount;
4854 }
4855 }
4856
4857 return result;
4858}
4859
4860// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004861spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004862 spv::Id typeId, spv::Id left, spv::Id right,
4863 glslang::TBasicType typeProxy, bool reduceComparison)
4864{
John Kessenich66011cb2018-03-06 16:12:04 -07004865 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4866 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004867 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004868
4869 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004870 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004871 bool comparison = false;
4872
4873 switch (op) {
4874 case glslang::EOpAdd:
4875 case glslang::EOpAddAssign:
4876 if (isFloat)
4877 binOp = spv::OpFAdd;
4878 else
4879 binOp = spv::OpIAdd;
4880 break;
4881 case glslang::EOpSub:
4882 case glslang::EOpSubAssign:
4883 if (isFloat)
4884 binOp = spv::OpFSub;
4885 else
4886 binOp = spv::OpISub;
4887 break;
4888 case glslang::EOpMul:
4889 case glslang::EOpMulAssign:
4890 if (isFloat)
4891 binOp = spv::OpFMul;
4892 else
4893 binOp = spv::OpIMul;
4894 break;
4895 case glslang::EOpVectorTimesScalar:
4896 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004897 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004898 if (builder.isVector(right))
4899 std::swap(left, right);
4900 assert(builder.isScalar(right));
4901 needMatchingVectors = false;
4902 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004903 } else if (isFloat)
4904 binOp = spv::OpFMul;
4905 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004906 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004907 break;
4908 case glslang::EOpVectorTimesMatrix:
4909 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004910 binOp = spv::OpVectorTimesMatrix;
4911 break;
4912 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004913 binOp = spv::OpMatrixTimesVector;
4914 break;
4915 case glslang::EOpMatrixTimesScalar:
4916 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004917 binOp = spv::OpMatrixTimesScalar;
4918 break;
4919 case glslang::EOpMatrixTimesMatrix:
4920 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004921 binOp = spv::OpMatrixTimesMatrix;
4922 break;
4923 case glslang::EOpOuterProduct:
4924 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004925 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004926 break;
4927
4928 case glslang::EOpDiv:
4929 case glslang::EOpDivAssign:
4930 if (isFloat)
4931 binOp = spv::OpFDiv;
4932 else if (isUnsigned)
4933 binOp = spv::OpUDiv;
4934 else
4935 binOp = spv::OpSDiv;
4936 break;
4937 case glslang::EOpMod:
4938 case glslang::EOpModAssign:
4939 if (isFloat)
4940 binOp = spv::OpFMod;
4941 else if (isUnsigned)
4942 binOp = spv::OpUMod;
4943 else
4944 binOp = spv::OpSMod;
4945 break;
4946 case glslang::EOpRightShift:
4947 case glslang::EOpRightShiftAssign:
4948 if (isUnsigned)
4949 binOp = spv::OpShiftRightLogical;
4950 else
4951 binOp = spv::OpShiftRightArithmetic;
4952 break;
4953 case glslang::EOpLeftShift:
4954 case glslang::EOpLeftShiftAssign:
4955 binOp = spv::OpShiftLeftLogical;
4956 break;
4957 case glslang::EOpAnd:
4958 case glslang::EOpAndAssign:
4959 binOp = spv::OpBitwiseAnd;
4960 break;
4961 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004962 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004963 binOp = spv::OpLogicalAnd;
4964 break;
4965 case glslang::EOpInclusiveOr:
4966 case glslang::EOpInclusiveOrAssign:
4967 binOp = spv::OpBitwiseOr;
4968 break;
4969 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004970 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004971 binOp = spv::OpLogicalOr;
4972 break;
4973 case glslang::EOpExclusiveOr:
4974 case glslang::EOpExclusiveOrAssign:
4975 binOp = spv::OpBitwiseXor;
4976 break;
4977 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004978 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004979 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
4981
4982 case glslang::EOpLessThan:
4983 case glslang::EOpGreaterThan:
4984 case glslang::EOpLessThanEqual:
4985 case glslang::EOpGreaterThanEqual:
4986 case glslang::EOpEqual:
4987 case glslang::EOpNotEqual:
4988 case glslang::EOpVectorEqual:
4989 case glslang::EOpVectorNotEqual:
4990 comparison = true;
4991 break;
4992 default:
4993 break;
4994 }
4995
John Kessenich7c1aa102015-10-15 13:29:11 -06004996 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004997 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004998 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004999 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5000 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005001 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005002
5003 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005004 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005005 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005006
qining25262b32016-05-06 17:25:16 -04005007 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005008 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005009 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005010 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005011 }
5012
5013 if (! comparison)
5014 return 0;
5015
John Kessenich7c1aa102015-10-15 13:29:11 -06005016 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005017
John Kessenich4583b612016-08-07 19:14:22 -06005018 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005019 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5020 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005021 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005022 return result;
5023 }
John Kessenich140f3df2015-06-26 16:58:36 -06005024
5025 switch (op) {
5026 case glslang::EOpLessThan:
5027 if (isFloat)
5028 binOp = spv::OpFOrdLessThan;
5029 else if (isUnsigned)
5030 binOp = spv::OpULessThan;
5031 else
5032 binOp = spv::OpSLessThan;
5033 break;
5034 case glslang::EOpGreaterThan:
5035 if (isFloat)
5036 binOp = spv::OpFOrdGreaterThan;
5037 else if (isUnsigned)
5038 binOp = spv::OpUGreaterThan;
5039 else
5040 binOp = spv::OpSGreaterThan;
5041 break;
5042 case glslang::EOpLessThanEqual:
5043 if (isFloat)
5044 binOp = spv::OpFOrdLessThanEqual;
5045 else if (isUnsigned)
5046 binOp = spv::OpULessThanEqual;
5047 else
5048 binOp = spv::OpSLessThanEqual;
5049 break;
5050 case glslang::EOpGreaterThanEqual:
5051 if (isFloat)
5052 binOp = spv::OpFOrdGreaterThanEqual;
5053 else if (isUnsigned)
5054 binOp = spv::OpUGreaterThanEqual;
5055 else
5056 binOp = spv::OpSGreaterThanEqual;
5057 break;
5058 case glslang::EOpEqual:
5059 case glslang::EOpVectorEqual:
5060 if (isFloat)
5061 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005062 else if (isBool)
5063 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005064 else
5065 binOp = spv::OpIEqual;
5066 break;
5067 case glslang::EOpNotEqual:
5068 case glslang::EOpVectorNotEqual:
5069 if (isFloat)
5070 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005071 else if (isBool)
5072 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005073 else
5074 binOp = spv::OpINotEqual;
5075 break;
5076 default:
5077 break;
5078 }
5079
qining25262b32016-05-06 17:25:16 -04005080 if (binOp != spv::OpNop) {
5081 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005082 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005083 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005084 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005085 }
John Kessenich140f3df2015-06-26 16:58:36 -06005086
5087 return 0;
5088}
5089
John Kessenich04bb8a02015-12-12 12:28:14 -07005090//
5091// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5092// These can be any of:
5093//
5094// matrix * scalar
5095// scalar * matrix
5096// matrix * matrix linear algebraic
5097// matrix * vector
5098// vector * matrix
5099// matrix * matrix componentwise
5100// matrix op matrix op in {+, -, /}
5101// matrix op scalar op in {+, -, /}
5102// scalar op matrix op in {+, -, /}
5103//
John Kessenichead86222018-03-28 18:01:20 -06005104spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5105 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005106{
5107 bool firstClass = true;
5108
5109 // First, handle first-class matrix operations (* and matrix/scalar)
5110 switch (op) {
5111 case spv::OpFDiv:
5112 if (builder.isMatrix(left) && builder.isScalar(right)) {
5113 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005114 spv::Id resultType = builder.getTypeId(right);
5115 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005116 op = spv::OpMatrixTimesScalar;
5117 } else
5118 firstClass = false;
5119 break;
5120 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005121 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005122 std::swap(left, right);
5123 assert(builder.isScalar(right));
5124 break;
5125 case spv::OpVectorTimesMatrix:
5126 assert(builder.isVector(left));
5127 assert(builder.isMatrix(right));
5128 break;
5129 case spv::OpMatrixTimesVector:
5130 assert(builder.isMatrix(left));
5131 assert(builder.isVector(right));
5132 break;
5133 case spv::OpMatrixTimesMatrix:
5134 assert(builder.isMatrix(left));
5135 assert(builder.isMatrix(right));
5136 break;
5137 default:
5138 firstClass = false;
5139 break;
5140 }
5141
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005142 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5143 firstClass = true;
5144
qining25262b32016-05-06 17:25:16 -04005145 if (firstClass) {
5146 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005147 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005148 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005149 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005150 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005151
LoopDawg592860c2016-06-09 08:57:35 -06005152 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005153 // The result type of all of them is the same type as the (a) matrix operand.
5154 // The algorithm is to:
5155 // - break the matrix(es) into vectors
5156 // - smear any scalar to a vector
5157 // - do vector operations
5158 // - make a matrix out the vector results
5159 switch (op) {
5160 case spv::OpFAdd:
5161 case spv::OpFSub:
5162 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005163 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005164 case spv::OpFMul:
5165 {
5166 // one time set up...
5167 bool leftMat = builder.isMatrix(left);
5168 bool rightMat = builder.isMatrix(right);
5169 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5170 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5171 spv::Id scalarType = builder.getScalarTypeId(typeId);
5172 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5173 std::vector<spv::Id> results;
5174 spv::Id smearVec = spv::NoResult;
5175 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005176 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005177 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005178 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005179
5180 // do each vector op
5181 for (unsigned int c = 0; c < numCols; ++c) {
5182 std::vector<unsigned int> indexes;
5183 indexes.push_back(c);
5184 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5185 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005186 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005187 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005188 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005189 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005190 }
5191
5192 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005193 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005194 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005195 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005196 }
5197 default:
5198 assert(0);
5199 return spv::NoResult;
5200 }
5201}
5202
John Kessenichead86222018-03-28 18:01:20 -06005203spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5204 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005205{
5206 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005207 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005208 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005209 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5210 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005211
5212 switch (op) {
5213 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005214 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005215 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005216 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005217 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005218 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005219 unaryOp = spv::OpSNegate;
5220 break;
5221
5222 case glslang::EOpLogicalNot:
5223 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 unaryOp = spv::OpLogicalNot;
5225 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 case glslang::EOpBitwiseNot:
5227 unaryOp = spv::OpNot;
5228 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005229
John Kessenich140f3df2015-06-26 16:58:36 -06005230 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
5236 case glslang::EOpTranspose:
5237 unaryOp = spv::OpTranspose;
5238 break;
5239
5240 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005241 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005242 break;
5243 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005244 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
5246 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005247 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 break;
5249 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005250 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
5255 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005257 break;
5258 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005259 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005260 break;
5261 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005262 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264
5265 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005269 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 break;
5271 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005272 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005273 break;
5274 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005275 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005276 break;
5277 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005278 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005279 break;
5280 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005281 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005282 break;
5283
5284 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005288 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005289 break;
5290
5291 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005292 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005295 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005296 break;
5297 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005298 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005299 break;
5300 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005301 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005302 break;
5303 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005304 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005305 break;
5306 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005307 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005308 break;
5309
5310 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005311 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005312 break;
5313 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005314 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 break;
5316 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005317 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005318 break;
5319 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005320 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005321 break;
5322 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005323 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328
5329 case glslang::EOpIsNan:
5330 unaryOp = spv::OpIsNan;
5331 break;
5332 case glslang::EOpIsInf:
5333 unaryOp = spv::OpIsInf;
5334 break;
LoopDawg592860c2016-06-09 08:57:35 -06005335 case glslang::EOpIsFinite:
5336 unaryOp = spv::OpIsFinite;
5337 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005338
Rex Xucbc426e2015-12-15 16:03:10 +08005339 case glslang::EOpFloatBitsToInt:
5340 case glslang::EOpFloatBitsToUint:
5341 case glslang::EOpIntBitsToFloat:
5342 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005343 case glslang::EOpDoubleBitsToInt64:
5344 case glslang::EOpDoubleBitsToUint64:
5345 case glslang::EOpInt64BitsToDouble:
5346 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005347 case glslang::EOpFloat16BitsToInt16:
5348 case glslang::EOpFloat16BitsToUint16:
5349 case glslang::EOpInt16BitsToFloat16:
5350 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005351 unaryOp = spv::OpBitcast;
5352 break;
5353
John Kessenich140f3df2015-06-26 16:58:36 -06005354 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005355 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005356 break;
5357 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005358 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005359 break;
5360 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005361 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005362 break;
5363 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005364 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005365 break;
5366 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005367 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005368 break;
5369 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005370 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005371 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005372 case glslang::EOpPackSnorm4x8:
5373 libCall = spv::GLSLstd450PackSnorm4x8;
5374 break;
5375 case glslang::EOpUnpackSnorm4x8:
5376 libCall = spv::GLSLstd450UnpackSnorm4x8;
5377 break;
5378 case glslang::EOpPackUnorm4x8:
5379 libCall = spv::GLSLstd450PackUnorm4x8;
5380 break;
5381 case glslang::EOpUnpackUnorm4x8:
5382 libCall = spv::GLSLstd450UnpackUnorm4x8;
5383 break;
5384 case glslang::EOpPackDouble2x32:
5385 libCall = spv::GLSLstd450PackDouble2x32;
5386 break;
5387 case glslang::EOpUnpackDouble2x32:
5388 libCall = spv::GLSLstd450UnpackDouble2x32;
5389 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005390
Rex Xu8ff43de2016-04-22 16:51:45 +08005391 case glslang::EOpPackInt2x32:
5392 case glslang::EOpUnpackInt2x32:
5393 case glslang::EOpPackUint2x32:
5394 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005395 case glslang::EOpPack16:
5396 case glslang::EOpPack32:
5397 case glslang::EOpPack64:
5398 case glslang::EOpUnpack32:
5399 case glslang::EOpUnpack16:
5400 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005401 case glslang::EOpPackInt2x16:
5402 case glslang::EOpUnpackInt2x16:
5403 case glslang::EOpPackUint2x16:
5404 case glslang::EOpUnpackUint2x16:
5405 case glslang::EOpPackInt4x16:
5406 case glslang::EOpUnpackInt4x16:
5407 case glslang::EOpPackUint4x16:
5408 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005409 case glslang::EOpPackFloat2x16:
5410 case glslang::EOpUnpackFloat2x16:
5411 unaryOp = spv::OpBitcast;
5412 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005413
John Kessenich140f3df2015-06-26 16:58:36 -06005414 case glslang::EOpDPdx:
5415 unaryOp = spv::OpDPdx;
5416 break;
5417 case glslang::EOpDPdy:
5418 unaryOp = spv::OpDPdy;
5419 break;
5420 case glslang::EOpFwidth:
5421 unaryOp = spv::OpFwidth;
5422 break;
5423 case glslang::EOpDPdxFine:
5424 unaryOp = spv::OpDPdxFine;
5425 break;
5426 case glslang::EOpDPdyFine:
5427 unaryOp = spv::OpDPdyFine;
5428 break;
5429 case glslang::EOpFwidthFine:
5430 unaryOp = spv::OpFwidthFine;
5431 break;
5432 case glslang::EOpDPdxCoarse:
5433 unaryOp = spv::OpDPdxCoarse;
5434 break;
5435 case glslang::EOpDPdyCoarse:
5436 unaryOp = spv::OpDPdyCoarse;
5437 break;
5438 case glslang::EOpFwidthCoarse:
5439 unaryOp = spv::OpFwidthCoarse;
5440 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005441 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005442#ifdef AMD_EXTENSIONS
5443 if (typeProxy == glslang::EbtFloat16)
5444 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5445#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005446 libCall = spv::GLSLstd450InterpolateAtCentroid;
5447 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005448 case glslang::EOpAny:
5449 unaryOp = spv::OpAny;
5450 break;
5451 case glslang::EOpAll:
5452 unaryOp = spv::OpAll;
5453 break;
5454
5455 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005456 if (isFloat)
5457 libCall = spv::GLSLstd450FAbs;
5458 else
5459 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005460 break;
5461 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005462 if (isFloat)
5463 libCall = spv::GLSLstd450FSign;
5464 else
5465 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 break;
5467
John Kessenichfc51d282015-08-19 13:34:18 -06005468 case glslang::EOpAtomicCounterIncrement:
5469 case glslang::EOpAtomicCounterDecrement:
5470 case glslang::EOpAtomicCounter:
5471 {
5472 // Handle all of the atomics in one place, in createAtomicOperation()
5473 std::vector<spv::Id> operands;
5474 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005475 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005476 }
5477
John Kessenichfc51d282015-08-19 13:34:18 -06005478 case glslang::EOpBitFieldReverse:
5479 unaryOp = spv::OpBitReverse;
5480 break;
5481 case glslang::EOpBitCount:
5482 unaryOp = spv::OpBitCount;
5483 break;
5484 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005485 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005486 break;
5487 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005488 if (isUnsigned)
5489 libCall = spv::GLSLstd450FindUMsb;
5490 else
5491 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005492 break;
5493
Rex Xu574ab042016-04-14 16:53:07 +08005494 case glslang::EOpBallot:
5495 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005496 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005497 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005498 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005499#ifdef AMD_EXTENSIONS
5500 case glslang::EOpMinInvocations:
5501 case glslang::EOpMaxInvocations:
5502 case glslang::EOpAddInvocations:
5503 case glslang::EOpMinInvocationsNonUniform:
5504 case glslang::EOpMaxInvocationsNonUniform:
5505 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005506 case glslang::EOpMinInvocationsInclusiveScan:
5507 case glslang::EOpMaxInvocationsInclusiveScan:
5508 case glslang::EOpAddInvocationsInclusiveScan:
5509 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5510 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5511 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5512 case glslang::EOpMinInvocationsExclusiveScan:
5513 case glslang::EOpMaxInvocationsExclusiveScan:
5514 case glslang::EOpAddInvocationsExclusiveScan:
5515 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5516 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5517 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005518#endif
Rex Xu51596642016-09-21 18:56:12 +08005519 {
5520 std::vector<spv::Id> operands;
5521 operands.push_back(operand);
5522 return createInvocationsOperation(op, typeId, operands, typeProxy);
5523 }
John Kessenich66011cb2018-03-06 16:12:04 -07005524 case glslang::EOpSubgroupAll:
5525 case glslang::EOpSubgroupAny:
5526 case glslang::EOpSubgroupAllEqual:
5527 case glslang::EOpSubgroupBroadcastFirst:
5528 case glslang::EOpSubgroupBallot:
5529 case glslang::EOpSubgroupInverseBallot:
5530 case glslang::EOpSubgroupBallotBitCount:
5531 case glslang::EOpSubgroupBallotInclusiveBitCount:
5532 case glslang::EOpSubgroupBallotExclusiveBitCount:
5533 case glslang::EOpSubgroupBallotFindLSB:
5534 case glslang::EOpSubgroupBallotFindMSB:
5535 case glslang::EOpSubgroupAdd:
5536 case glslang::EOpSubgroupMul:
5537 case glslang::EOpSubgroupMin:
5538 case glslang::EOpSubgroupMax:
5539 case glslang::EOpSubgroupAnd:
5540 case glslang::EOpSubgroupOr:
5541 case glslang::EOpSubgroupXor:
5542 case glslang::EOpSubgroupInclusiveAdd:
5543 case glslang::EOpSubgroupInclusiveMul:
5544 case glslang::EOpSubgroupInclusiveMin:
5545 case glslang::EOpSubgroupInclusiveMax:
5546 case glslang::EOpSubgroupInclusiveAnd:
5547 case glslang::EOpSubgroupInclusiveOr:
5548 case glslang::EOpSubgroupInclusiveXor:
5549 case glslang::EOpSubgroupExclusiveAdd:
5550 case glslang::EOpSubgroupExclusiveMul:
5551 case glslang::EOpSubgroupExclusiveMin:
5552 case glslang::EOpSubgroupExclusiveMax:
5553 case glslang::EOpSubgroupExclusiveAnd:
5554 case glslang::EOpSubgroupExclusiveOr:
5555 case glslang::EOpSubgroupExclusiveXor:
5556 case glslang::EOpSubgroupQuadSwapHorizontal:
5557 case glslang::EOpSubgroupQuadSwapVertical:
5558 case glslang::EOpSubgroupQuadSwapDiagonal: {
5559 std::vector<spv::Id> operands;
5560 operands.push_back(operand);
5561 return createSubgroupOperation(op, typeId, operands, typeProxy);
5562 }
Rex Xu9d93a232016-05-05 12:30:44 +08005563#ifdef AMD_EXTENSIONS
5564 case glslang::EOpMbcnt:
5565 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5566 libCall = spv::MbcntAMD;
5567 break;
5568
5569 case glslang::EOpCubeFaceIndex:
5570 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5571 libCall = spv::CubeFaceIndexAMD;
5572 break;
5573
5574 case glslang::EOpCubeFaceCoord:
5575 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5576 libCall = spv::CubeFaceCoordAMD;
5577 break;
5578#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005579#ifdef NV_EXTENSIONS
5580 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005581 unaryOp = spv::OpGroupNonUniformPartitionNV;
5582 break;
5583#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005584 case glslang::EOpConstructReference:
5585 unaryOp = spv::OpBitcast;
5586 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005587
5588 case glslang::EOpCopyObject:
5589 unaryOp = spv::OpCopyObject;
5590 break;
5591
John Kessenich140f3df2015-06-26 16:58:36 -06005592 default:
5593 return 0;
5594 }
5595
5596 spv::Id id;
5597 if (libCall >= 0) {
5598 std::vector<spv::Id> args;
5599 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005600 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005601 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005602 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005603 }
John Kessenich140f3df2015-06-26 16:58:36 -06005604
John Kessenichead86222018-03-28 18:01:20 -06005605 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005606 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005607 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005608}
5609
John Kessenich7a53f762016-01-20 11:19:27 -07005610// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005611spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5612 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005613{
5614 // Handle unary operations vector by vector.
5615 // The result type is the same type as the original type.
5616 // The algorithm is to:
5617 // - break the matrix into vectors
5618 // - apply the operation to each vector
5619 // - make a matrix out the vector results
5620
5621 // get the types sorted out
5622 int numCols = builder.getNumColumns(operand);
5623 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005624 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5625 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005626 std::vector<spv::Id> results;
5627
5628 // do each vector op
5629 for (int c = 0; c < numCols; ++c) {
5630 std::vector<unsigned int> indexes;
5631 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005632 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5633 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005634 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005635 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005636 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005637 }
5638
5639 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005640 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005641 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005642 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005643}
5644
John Kessenichad7645f2018-06-04 19:11:25 -06005645// For converting integers where both the bitwidth and the signedness could
5646// change, but only do the width change here. The caller is still responsible
5647// for the signedness conversion.
5648spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005649{
John Kessenichad7645f2018-06-04 19:11:25 -06005650 // Get the result type width, based on the type to convert to.
5651 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005652 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005653 case glslang::EOpConvInt16ToUint8:
5654 case glslang::EOpConvIntToUint8:
5655 case glslang::EOpConvInt64ToUint8:
5656 case glslang::EOpConvUint16ToInt8:
5657 case glslang::EOpConvUintToInt8:
5658 case glslang::EOpConvUint64ToInt8:
5659 width = 8;
5660 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005661 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005662 case glslang::EOpConvIntToUint16:
5663 case glslang::EOpConvInt64ToUint16:
5664 case glslang::EOpConvUint8ToInt16:
5665 case glslang::EOpConvUintToInt16:
5666 case glslang::EOpConvUint64ToInt16:
5667 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005668 break;
5669 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005670 case glslang::EOpConvInt16ToUint:
5671 case glslang::EOpConvInt64ToUint:
5672 case glslang::EOpConvUint8ToInt:
5673 case glslang::EOpConvUint16ToInt:
5674 case glslang::EOpConvUint64ToInt:
5675 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005676 break;
5677 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005678 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005679 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005680 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005681 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005682 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005683 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005684 break;
5685
5686 default:
5687 assert(false && "Default missing");
5688 break;
5689 }
5690
John Kessenichad7645f2018-06-04 19:11:25 -06005691 // Get the conversion operation and result type,
5692 // based on the target width, but the source type.
5693 spv::Id type = spv::NoType;
5694 spv::Op convOp = spv::OpNop;
5695 switch(op) {
5696 case glslang::EOpConvInt8ToUint16:
5697 case glslang::EOpConvInt8ToUint:
5698 case glslang::EOpConvInt8ToUint64:
5699 case glslang::EOpConvInt16ToUint8:
5700 case glslang::EOpConvInt16ToUint:
5701 case glslang::EOpConvInt16ToUint64:
5702 case glslang::EOpConvIntToUint8:
5703 case glslang::EOpConvIntToUint16:
5704 case glslang::EOpConvIntToUint64:
5705 case glslang::EOpConvInt64ToUint8:
5706 case glslang::EOpConvInt64ToUint16:
5707 case glslang::EOpConvInt64ToUint:
5708 convOp = spv::OpSConvert;
5709 type = builder.makeIntType(width);
5710 break;
5711 default:
5712 convOp = spv::OpUConvert;
5713 type = builder.makeUintType(width);
5714 break;
5715 }
5716
John Kessenich66011cb2018-03-06 16:12:04 -07005717 if (vectorSize > 0)
5718 type = builder.makeVectorType(type, vectorSize);
5719
John Kessenichad7645f2018-06-04 19:11:25 -06005720 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005721}
5722
John Kessenichead86222018-03-28 18:01:20 -06005723spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5724 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005725{
5726 spv::Op convOp = spv::OpNop;
5727 spv::Id zero = 0;
5728 spv::Id one = 0;
5729
5730 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5731
5732 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005733 case glslang::EOpConvInt8ToBool:
5734 case glslang::EOpConvUint8ToBool:
5735 zero = builder.makeUint8Constant(0);
5736 zero = makeSmearedConstant(zero, vectorSize);
5737 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005738 case glslang::EOpConvInt16ToBool:
5739 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005740 zero = builder.makeUint16Constant(0);
5741 zero = makeSmearedConstant(zero, vectorSize);
5742 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5743 case glslang::EOpConvIntToBool:
5744 case glslang::EOpConvUintToBool:
5745 zero = builder.makeUintConstant(0);
5746 zero = makeSmearedConstant(zero, vectorSize);
5747 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5748 case glslang::EOpConvInt64ToBool:
5749 case glslang::EOpConvUint64ToBool:
5750 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005751 zero = makeSmearedConstant(zero, vectorSize);
5752 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5753
5754 case glslang::EOpConvFloatToBool:
5755 zero = builder.makeFloatConstant(0.0F);
5756 zero = makeSmearedConstant(zero, vectorSize);
5757 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5758
5759 case glslang::EOpConvDoubleToBool:
5760 zero = builder.makeDoubleConstant(0.0);
5761 zero = makeSmearedConstant(zero, vectorSize);
5762 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5763
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005764 case glslang::EOpConvFloat16ToBool:
5765 zero = builder.makeFloat16Constant(0.0F);
5766 zero = makeSmearedConstant(zero, vectorSize);
5767 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005768
John Kessenich140f3df2015-06-26 16:58:36 -06005769 case glslang::EOpConvBoolToFloat:
5770 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005771 zero = builder.makeFloatConstant(0.0F);
5772 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005773 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005774
John Kessenich140f3df2015-06-26 16:58:36 -06005775 case glslang::EOpConvBoolToDouble:
5776 convOp = spv::OpSelect;
5777 zero = builder.makeDoubleConstant(0.0);
5778 one = builder.makeDoubleConstant(1.0);
5779 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005780
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005781 case glslang::EOpConvBoolToFloat16:
5782 convOp = spv::OpSelect;
5783 zero = builder.makeFloat16Constant(0.0F);
5784 one = builder.makeFloat16Constant(1.0F);
5785 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005786
5787 case glslang::EOpConvBoolToInt8:
5788 zero = builder.makeInt8Constant(0);
5789 one = builder.makeInt8Constant(1);
5790 convOp = spv::OpSelect;
5791 break;
5792
5793 case glslang::EOpConvBoolToUint8:
5794 zero = builder.makeUint8Constant(0);
5795 one = builder.makeUint8Constant(1);
5796 convOp = spv::OpSelect;
5797 break;
5798
5799 case glslang::EOpConvBoolToInt16:
5800 zero = builder.makeInt16Constant(0);
5801 one = builder.makeInt16Constant(1);
5802 convOp = spv::OpSelect;
5803 break;
5804
5805 case glslang::EOpConvBoolToUint16:
5806 zero = builder.makeUint16Constant(0);
5807 one = builder.makeUint16Constant(1);
5808 convOp = spv::OpSelect;
5809 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005810
John Kessenich140f3df2015-06-26 16:58:36 -06005811 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005812 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005813 if (op == glslang::EOpConvBoolToInt64)
5814 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005815 else
5816 zero = builder.makeIntConstant(0);
5817
5818 if (op == glslang::EOpConvBoolToInt64)
5819 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005820 else
5821 one = builder.makeIntConstant(1);
5822
John Kessenich140f3df2015-06-26 16:58:36 -06005823 convOp = spv::OpSelect;
5824 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005825
John Kessenich140f3df2015-06-26 16:58:36 -06005826 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005827 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005828 if (op == glslang::EOpConvBoolToUint64)
5829 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005830 else
5831 zero = builder.makeUintConstant(0);
5832
5833 if (op == glslang::EOpConvBoolToUint64)
5834 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005835 else
5836 one = builder.makeUintConstant(1);
5837
John Kessenich140f3df2015-06-26 16:58:36 -06005838 convOp = spv::OpSelect;
5839 break;
5840
John Kessenich66011cb2018-03-06 16:12:04 -07005841 case glslang::EOpConvInt8ToFloat16:
5842 case glslang::EOpConvInt8ToFloat:
5843 case glslang::EOpConvInt8ToDouble:
5844 case glslang::EOpConvInt16ToFloat16:
5845 case glslang::EOpConvInt16ToFloat:
5846 case glslang::EOpConvInt16ToDouble:
5847 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005848 case glslang::EOpConvIntToFloat:
5849 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005850 case glslang::EOpConvInt64ToFloat:
5851 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005852 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005853 convOp = spv::OpConvertSToF;
5854 break;
5855
John Kessenich66011cb2018-03-06 16:12:04 -07005856 case glslang::EOpConvUint8ToFloat16:
5857 case glslang::EOpConvUint8ToFloat:
5858 case glslang::EOpConvUint8ToDouble:
5859 case glslang::EOpConvUint16ToFloat16:
5860 case glslang::EOpConvUint16ToFloat:
5861 case glslang::EOpConvUint16ToDouble:
5862 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005863 case glslang::EOpConvUintToFloat:
5864 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005865 case glslang::EOpConvUint64ToFloat:
5866 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005867 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005868 convOp = spv::OpConvertUToF;
5869 break;
5870
5871 case glslang::EOpConvDoubleToFloat:
5872 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005873 case glslang::EOpConvDoubleToFloat16:
5874 case glslang::EOpConvFloat16ToDouble:
5875 case glslang::EOpConvFloatToFloat16:
5876 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005877 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005878 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005879 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005880 break;
5881
John Kessenich66011cb2018-03-06 16:12:04 -07005882 case glslang::EOpConvFloat16ToInt8:
5883 case glslang::EOpConvFloatToInt8:
5884 case glslang::EOpConvDoubleToInt8:
5885 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005886 case glslang::EOpConvFloatToInt16:
5887 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005888 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005889 case glslang::EOpConvFloatToInt:
5890 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005891 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005892 case glslang::EOpConvFloatToInt64:
5893 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005894 convOp = spv::OpConvertFToS;
5895 break;
5896
John Kessenich66011cb2018-03-06 16:12:04 -07005897 case glslang::EOpConvUint8ToInt8:
5898 case glslang::EOpConvInt8ToUint8:
5899 case glslang::EOpConvUint16ToInt16:
5900 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005901 case glslang::EOpConvUintToInt:
5902 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005903 case glslang::EOpConvUint64ToInt64:
5904 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005905 if (builder.isInSpecConstCodeGenMode()) {
5906 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005907 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5908 zero = builder.makeUint8Constant(0);
5909 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005910 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005911 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5912 zero = builder.makeUint64Constant(0);
5913 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005914 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005915 }
qining189b2032016-04-12 23:16:20 -04005916 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005917 // Use OpIAdd, instead of OpBitcast to do the conversion when
5918 // generating for OpSpecConstantOp instruction.
5919 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5920 }
5921 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005922 convOp = spv::OpBitcast;
5923 break;
5924
John Kessenich66011cb2018-03-06 16:12:04 -07005925 case glslang::EOpConvFloat16ToUint8:
5926 case glslang::EOpConvFloatToUint8:
5927 case glslang::EOpConvDoubleToUint8:
5928 case glslang::EOpConvFloat16ToUint16:
5929 case glslang::EOpConvFloatToUint16:
5930 case glslang::EOpConvDoubleToUint16:
5931 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005932 case glslang::EOpConvFloatToUint:
5933 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005934 case glslang::EOpConvFloatToUint64:
5935 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005936 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005937 convOp = spv::OpConvertFToU;
5938 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005939
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpConvInt8ToInt16:
5941 case glslang::EOpConvInt8ToInt:
5942 case glslang::EOpConvInt8ToInt64:
5943 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005944 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005945 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005946 case glslang::EOpConvIntToInt8:
5947 case glslang::EOpConvIntToInt16:
5948 case glslang::EOpConvIntToInt64:
5949 case glslang::EOpConvInt64ToInt8:
5950 case glslang::EOpConvInt64ToInt16:
5951 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005952 convOp = spv::OpSConvert;
5953 break;
5954
John Kessenich66011cb2018-03-06 16:12:04 -07005955 case glslang::EOpConvUint8ToUint16:
5956 case glslang::EOpConvUint8ToUint:
5957 case glslang::EOpConvUint8ToUint64:
5958 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005959 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005960 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005961 case glslang::EOpConvUintToUint8:
5962 case glslang::EOpConvUintToUint16:
5963 case glslang::EOpConvUintToUint64:
5964 case glslang::EOpConvUint64ToUint8:
5965 case glslang::EOpConvUint64ToUint16:
5966 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005967 convOp = spv::OpUConvert;
5968 break;
5969
John Kessenich66011cb2018-03-06 16:12:04 -07005970 case glslang::EOpConvInt8ToUint16:
5971 case glslang::EOpConvInt8ToUint:
5972 case glslang::EOpConvInt8ToUint64:
5973 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005974 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005975 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005976 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005977 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005978 case glslang::EOpConvIntToUint64:
5979 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005980 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005981 case glslang::EOpConvInt64ToUint:
5982 case glslang::EOpConvUint8ToInt16:
5983 case glslang::EOpConvUint8ToInt:
5984 case glslang::EOpConvUint8ToInt64:
5985 case glslang::EOpConvUint16ToInt8:
5986 case glslang::EOpConvUint16ToInt:
5987 case glslang::EOpConvUint16ToInt64:
5988 case glslang::EOpConvUintToInt8:
5989 case glslang::EOpConvUintToInt16:
5990 case glslang::EOpConvUintToInt64:
5991 case glslang::EOpConvUint64ToInt8:
5992 case glslang::EOpConvUint64ToInt16:
5993 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005994 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005995 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005996
5997 if (builder.isInSpecConstCodeGenMode()) {
5998 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005999 switch(op) {
6000 case glslang::EOpConvInt16ToUint8:
6001 case glslang::EOpConvIntToUint8:
6002 case glslang::EOpConvInt64ToUint8:
6003 case glslang::EOpConvUint16ToInt8:
6004 case glslang::EOpConvUintToInt8:
6005 case glslang::EOpConvUint64ToInt8:
6006 zero = builder.makeUint8Constant(0);
6007 break;
6008 case glslang::EOpConvInt8ToUint16:
6009 case glslang::EOpConvIntToUint16:
6010 case glslang::EOpConvInt64ToUint16:
6011 case glslang::EOpConvUint8ToInt16:
6012 case glslang::EOpConvUintToInt16:
6013 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006014 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006015 break;
6016 case glslang::EOpConvInt8ToUint:
6017 case glslang::EOpConvInt16ToUint:
6018 case glslang::EOpConvInt64ToUint:
6019 case glslang::EOpConvUint8ToInt:
6020 case glslang::EOpConvUint16ToInt:
6021 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006022 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006023 break;
6024 case glslang::EOpConvInt8ToUint64:
6025 case glslang::EOpConvInt16ToUint64:
6026 case glslang::EOpConvIntToUint64:
6027 case glslang::EOpConvUint8ToInt64:
6028 case glslang::EOpConvUint16ToInt64:
6029 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006030 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006031 break;
6032 default:
6033 assert(false && "Default missing");
6034 break;
6035 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006036 zero = makeSmearedConstant(zero, vectorSize);
6037 // Use OpIAdd, instead of OpBitcast to do the conversion when
6038 // generating for OpSpecConstantOp instruction.
6039 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6040 }
6041 // For normal run-time conversion instruction, use OpBitcast.
6042 convOp = spv::OpBitcast;
6043 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006044 case glslang::EOpConvUint64ToPtr:
6045 convOp = spv::OpConvertUToPtr;
6046 break;
6047 case glslang::EOpConvPtrToUint64:
6048 convOp = spv::OpConvertPtrToU;
6049 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006050 default:
6051 break;
6052 }
6053
6054 spv::Id result = 0;
6055 if (convOp == spv::OpNop)
6056 return result;
6057
6058 if (convOp == spv::OpSelect) {
6059 zero = makeSmearedConstant(zero, vectorSize);
6060 one = makeSmearedConstant(one, vectorSize);
6061 result = builder.createTriOp(convOp, destType, operand, one, zero);
6062 } else
6063 result = builder.createUnaryOp(convOp, destType, operand);
6064
John Kessenichead86222018-03-28 18:01:20 -06006065 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006066 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006067 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006068}
6069
6070spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6071{
6072 if (vectorSize == 0)
6073 return constant;
6074
6075 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6076 std::vector<spv::Id> components;
6077 for (int c = 0; c < vectorSize; ++c)
6078 components.push_back(constant);
6079 return builder.makeCompositeConstant(vectorTypeId, components);
6080}
6081
John Kessenich426394d2015-07-23 10:22:48 -06006082// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006083spv::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 -06006084{
6085 spv::Op opCode = spv::OpNop;
6086
6087 switch (op) {
6088 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006089 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006090 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006091 opCode = spv::OpAtomicIAdd;
6092 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006093 case glslang::EOpAtomicCounterSubtract:
6094 opCode = spv::OpAtomicISub;
6095 break;
John Kessenich426394d2015-07-23 10:22:48 -06006096 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006097 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006098 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006099 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006100 break;
6101 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006102 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006103 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006104 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006105 break;
6106 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006107 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006108 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006109 opCode = spv::OpAtomicAnd;
6110 break;
6111 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006112 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006113 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006114 opCode = spv::OpAtomicOr;
6115 break;
6116 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006117 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006118 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006119 opCode = spv::OpAtomicXor;
6120 break;
6121 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006122 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006123 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006124 opCode = spv::OpAtomicExchange;
6125 break;
6126 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006127 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006128 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006129 opCode = spv::OpAtomicCompareExchange;
6130 break;
6131 case glslang::EOpAtomicCounterIncrement:
6132 opCode = spv::OpAtomicIIncrement;
6133 break;
6134 case glslang::EOpAtomicCounterDecrement:
6135 opCode = spv::OpAtomicIDecrement;
6136 break;
6137 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006138 case glslang::EOpImageAtomicLoad:
6139 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006140 opCode = spv::OpAtomicLoad;
6141 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006142 case glslang::EOpAtomicStore:
6143 case glslang::EOpImageAtomicStore:
6144 opCode = spv::OpAtomicStore;
6145 break;
John Kessenich426394d2015-07-23 10:22:48 -06006146 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006147 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006148 break;
6149 }
6150
Rex Xue8fe8b02017-09-26 15:42:56 +08006151 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6152 builder.addCapability(spv::CapabilityInt64Atomics);
6153
John Kessenich426394d2015-07-23 10:22:48 -06006154 // Sort out the operands
6155 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006156 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006157 // - compare-exchange swaps the value and comparator
6158 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006159 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006160 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6161 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6162 spv::Id scopeId;
6163 if (glslangIntermediate->usingVulkanMemoryModel()) {
6164 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6165 } else {
6166 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6167 }
6168 // semantics default to relaxed
6169 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6170 spv::Id semanticsId2 = semanticsId;
6171
6172 pointerId = operands[0];
6173 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6174 // no additional operands
6175 } else if (opCode == spv::OpAtomicCompareExchange) {
6176 compareId = operands[1];
6177 valueId = operands[2];
6178 if (operands.size() > 3) {
6179 scopeId = operands[3];
6180 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6181 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6182 }
6183 } else if (opCode == spv::OpAtomicLoad) {
6184 if (operands.size() > 1) {
6185 scopeId = operands[1];
6186 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6187 }
6188 } else {
6189 // atomic store or RMW
6190 valueId = operands[1];
6191 if (operands.size() > 2) {
6192 scopeId = operands[2];
6193 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6194 }
Rex Xu04db3f52015-09-16 11:44:02 +08006195 }
John Kessenich426394d2015-07-23 10:22:48 -06006196
Jeff Bolz36831c92018-09-05 10:11:41 -05006197 // Check for capabilities
6198 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6199 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6200 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6201 }
John Kessenich426394d2015-07-23 10:22:48 -06006202
Jeff Bolz36831c92018-09-05 10:11:41 -05006203 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6204 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6205 }
John Kessenich48d6e792017-10-06 21:21:48 -06006206
Jeff Bolz36831c92018-09-05 10:11:41 -05006207 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6208 spvAtomicOperands.push_back(pointerId);
6209 spvAtomicOperands.push_back(scopeId);
6210 spvAtomicOperands.push_back(semanticsId);
6211 if (opCode == spv::OpAtomicCompareExchange) {
6212 spvAtomicOperands.push_back(semanticsId2);
6213 spvAtomicOperands.push_back(valueId);
6214 spvAtomicOperands.push_back(compareId);
6215 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6216 spvAtomicOperands.push_back(valueId);
6217 }
John Kessenich48d6e792017-10-06 21:21:48 -06006218
Jeff Bolz36831c92018-09-05 10:11:41 -05006219 if (opCode == spv::OpAtomicStore) {
6220 builder.createNoResultOp(opCode, spvAtomicOperands);
6221 return 0;
6222 } else {
6223 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6224
6225 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6226 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6227 if (op == glslang::EOpAtomicCounterDecrement)
6228 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6229
6230 return resultId;
6231 }
John Kessenich426394d2015-07-23 10:22:48 -06006232}
6233
John Kessenich91cef522016-05-05 16:45:40 -06006234// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006235spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006236{
Corentin Walleze7061422018-08-08 15:20:15 +02006237#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006238 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6239 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006240#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006241
Rex Xu51596642016-09-21 18:56:12 +08006242 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006243 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006244 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6245
chaocf200da82016-12-20 12:44:35 -08006246 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6247 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006248 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6249 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006250 } else if (op == glslang::EOpAnyInvocation ||
6251 op == glslang::EOpAllInvocations ||
6252 op == glslang::EOpAllInvocationsEqual) {
6253 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6254 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006255 } else {
6256 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006257#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006258 if (op == glslang::EOpMinInvocationsNonUniform ||
6259 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006260 op == glslang::EOpAddInvocationsNonUniform ||
6261 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6262 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6263 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6264 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6265 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6266 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006267 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006268#endif
Rex Xu51596642016-09-21 18:56:12 +08006269
Rex Xu9d93a232016-05-05 12:30:44 +08006270#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006271 switch (op) {
6272 case glslang::EOpMinInvocations:
6273 case glslang::EOpMaxInvocations:
6274 case glslang::EOpAddInvocations:
6275 case glslang::EOpMinInvocationsNonUniform:
6276 case glslang::EOpMaxInvocationsNonUniform:
6277 case glslang::EOpAddInvocationsNonUniform:
6278 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006279 break;
6280 case glslang::EOpMinInvocationsInclusiveScan:
6281 case glslang::EOpMaxInvocationsInclusiveScan:
6282 case glslang::EOpAddInvocationsInclusiveScan:
6283 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6284 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6285 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6286 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006287 break;
6288 case glslang::EOpMinInvocationsExclusiveScan:
6289 case glslang::EOpMaxInvocationsExclusiveScan:
6290 case glslang::EOpAddInvocationsExclusiveScan:
6291 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6292 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6293 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6294 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006295 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006296 default:
6297 break;
Rex Xu430ef402016-10-14 17:22:23 +08006298 }
John Kessenich149afc32018-08-14 13:31:43 -06006299 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6300 spvGroupOperands.push_back(scope);
6301 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006302 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006303 spvGroupOperands.push_back(groupOp);
6304 }
Rex Xu9d93a232016-05-05 12:30:44 +08006305#endif
Rex Xu51596642016-09-21 18:56:12 +08006306 }
6307
John Kessenich149afc32018-08-14 13:31:43 -06006308 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6309 spv::IdImmediate op = { true, *opIt };
6310 spvGroupOperands.push_back(op);
6311 }
John Kessenich91cef522016-05-05 16:45:40 -06006312
6313 switch (op) {
6314 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006315 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006316 break;
John Kessenich91cef522016-05-05 16:45:40 -06006317 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006318 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006319 break;
John Kessenich91cef522016-05-05 16:45:40 -06006320 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006321 opCode = spv::OpSubgroupAllEqualKHR;
6322 break;
Rex Xu51596642016-09-21 18:56:12 +08006323 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006324 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006325 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006326 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006327 break;
6328 case glslang::EOpReadFirstInvocation:
6329 opCode = spv::OpSubgroupFirstInvocationKHR;
6330 break;
6331 case glslang::EOpBallot:
6332 {
6333 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6334 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6335 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6336 //
6337 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6338 //
6339 spv::Id uintType = builder.makeUintType(32);
6340 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6341 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6342
6343 std::vector<spv::Id> components;
6344 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6345 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6346
6347 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6348 return builder.createUnaryOp(spv::OpBitcast, typeId,
6349 builder.createCompositeConstruct(uvec2Type, components));
6350 }
6351
Rex Xu9d93a232016-05-05 12:30:44 +08006352#ifdef AMD_EXTENSIONS
6353 case glslang::EOpMinInvocations:
6354 case glslang::EOpMaxInvocations:
6355 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006356 case glslang::EOpMinInvocationsInclusiveScan:
6357 case glslang::EOpMaxInvocationsInclusiveScan:
6358 case glslang::EOpAddInvocationsInclusiveScan:
6359 case glslang::EOpMinInvocationsExclusiveScan:
6360 case glslang::EOpMaxInvocationsExclusiveScan:
6361 case glslang::EOpAddInvocationsExclusiveScan:
6362 if (op == glslang::EOpMinInvocations ||
6363 op == glslang::EOpMinInvocationsInclusiveScan ||
6364 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006365 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006366 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006367 else {
6368 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006369 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006370 else
Rex Xu51596642016-09-21 18:56:12 +08006371 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006372 }
Rex Xu430ef402016-10-14 17:22:23 +08006373 } else if (op == glslang::EOpMaxInvocations ||
6374 op == glslang::EOpMaxInvocationsInclusiveScan ||
6375 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006376 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006377 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006378 else {
6379 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006380 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006381 else
Rex Xu51596642016-09-21 18:56:12 +08006382 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006383 }
6384 } else {
6385 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006386 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006387 else
Rex Xu51596642016-09-21 18:56:12 +08006388 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006389 }
6390
Rex Xu2bbbe062016-08-23 15:41:05 +08006391 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006392 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006393
6394 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006395 case glslang::EOpMinInvocationsNonUniform:
6396 case glslang::EOpMaxInvocationsNonUniform:
6397 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006398 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6399 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6400 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6401 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6402 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6403 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6404 if (op == glslang::EOpMinInvocationsNonUniform ||
6405 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6406 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006407 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006408 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006409 else {
6410 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006411 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006412 else
Rex Xu51596642016-09-21 18:56:12 +08006413 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006414 }
6415 }
Rex Xu430ef402016-10-14 17:22:23 +08006416 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6417 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6418 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006419 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006420 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006421 else {
6422 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006423 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006424 else
Rex Xu51596642016-09-21 18:56:12 +08006425 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006426 }
6427 }
6428 else {
6429 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006430 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006431 else
Rex Xu51596642016-09-21 18:56:12 +08006432 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006433 }
6434
Rex Xu2bbbe062016-08-23 15:41:05 +08006435 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006436 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006437
6438 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006439#endif
John Kessenich91cef522016-05-05 16:45:40 -06006440 default:
6441 logger->missingFunctionality("invocation operation");
6442 return spv::NoResult;
6443 }
Rex Xu51596642016-09-21 18:56:12 +08006444
6445 assert(opCode != spv::OpNop);
6446 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006447}
6448
Rex Xu2bbbe062016-08-23 15:41:05 +08006449// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006450spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6451 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006452{
Rex Xub7072052016-09-26 15:53:40 +08006453#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006454 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6455 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006456 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006457 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006458 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6459 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6460 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006461#else
6462 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6463 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006464 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6465 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006466#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006467
6468 // Handle group invocation operations scalar by scalar.
6469 // The result type is the same type as the original type.
6470 // The algorithm is to:
6471 // - break the vector into scalars
6472 // - apply the operation to each scalar
6473 // - make a vector out the scalar results
6474
6475 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006476 int numComponents = builder.getNumComponents(operands[0]);
6477 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006478 std::vector<spv::Id> results;
6479
6480 // do each scalar op
6481 for (int comp = 0; comp < numComponents; ++comp) {
6482 std::vector<unsigned int> indexes;
6483 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006484 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6485 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006486 if (op == spv::OpSubgroupReadInvocationKHR) {
6487 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006488 spv::IdImmediate operand = { true, operands[1] };
6489 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006490 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006491 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6492 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006493 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006494 spv::IdImmediate operand = { true, operands[1] };
6495 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006496 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006497 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6498 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006499 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006500 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006501 spvGroupOperands.push_back(scalar);
6502 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006503
Rex Xub7072052016-09-26 15:53:40 +08006504 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006505 }
6506
6507 // put the pieces together
6508 return builder.createCompositeConstruct(typeId, results);
6509}
Rex Xu2bbbe062016-08-23 15:41:05 +08006510
John Kessenich66011cb2018-03-06 16:12:04 -07006511// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006512spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6513 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006514{
6515 // Add the required capabilities.
6516 switch (op) {
6517 case glslang::EOpSubgroupElect:
6518 builder.addCapability(spv::CapabilityGroupNonUniform);
6519 break;
6520 case glslang::EOpSubgroupAll:
6521 case glslang::EOpSubgroupAny:
6522 case glslang::EOpSubgroupAllEqual:
6523 builder.addCapability(spv::CapabilityGroupNonUniform);
6524 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6525 break;
6526 case glslang::EOpSubgroupBroadcast:
6527 case glslang::EOpSubgroupBroadcastFirst:
6528 case glslang::EOpSubgroupBallot:
6529 case glslang::EOpSubgroupInverseBallot:
6530 case glslang::EOpSubgroupBallotBitExtract:
6531 case glslang::EOpSubgroupBallotBitCount:
6532 case glslang::EOpSubgroupBallotInclusiveBitCount:
6533 case glslang::EOpSubgroupBallotExclusiveBitCount:
6534 case glslang::EOpSubgroupBallotFindLSB:
6535 case glslang::EOpSubgroupBallotFindMSB:
6536 builder.addCapability(spv::CapabilityGroupNonUniform);
6537 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6538 break;
6539 case glslang::EOpSubgroupShuffle:
6540 case glslang::EOpSubgroupShuffleXor:
6541 builder.addCapability(spv::CapabilityGroupNonUniform);
6542 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6543 break;
6544 case glslang::EOpSubgroupShuffleUp:
6545 case glslang::EOpSubgroupShuffleDown:
6546 builder.addCapability(spv::CapabilityGroupNonUniform);
6547 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6548 break;
6549 case glslang::EOpSubgroupAdd:
6550 case glslang::EOpSubgroupMul:
6551 case glslang::EOpSubgroupMin:
6552 case glslang::EOpSubgroupMax:
6553 case glslang::EOpSubgroupAnd:
6554 case glslang::EOpSubgroupOr:
6555 case glslang::EOpSubgroupXor:
6556 case glslang::EOpSubgroupInclusiveAdd:
6557 case glslang::EOpSubgroupInclusiveMul:
6558 case glslang::EOpSubgroupInclusiveMin:
6559 case glslang::EOpSubgroupInclusiveMax:
6560 case glslang::EOpSubgroupInclusiveAnd:
6561 case glslang::EOpSubgroupInclusiveOr:
6562 case glslang::EOpSubgroupInclusiveXor:
6563 case glslang::EOpSubgroupExclusiveAdd:
6564 case glslang::EOpSubgroupExclusiveMul:
6565 case glslang::EOpSubgroupExclusiveMin:
6566 case glslang::EOpSubgroupExclusiveMax:
6567 case glslang::EOpSubgroupExclusiveAnd:
6568 case glslang::EOpSubgroupExclusiveOr:
6569 case glslang::EOpSubgroupExclusiveXor:
6570 builder.addCapability(spv::CapabilityGroupNonUniform);
6571 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6572 break;
6573 case glslang::EOpSubgroupClusteredAdd:
6574 case glslang::EOpSubgroupClusteredMul:
6575 case glslang::EOpSubgroupClusteredMin:
6576 case glslang::EOpSubgroupClusteredMax:
6577 case glslang::EOpSubgroupClusteredAnd:
6578 case glslang::EOpSubgroupClusteredOr:
6579 case glslang::EOpSubgroupClusteredXor:
6580 builder.addCapability(spv::CapabilityGroupNonUniform);
6581 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6582 break;
6583 case glslang::EOpSubgroupQuadBroadcast:
6584 case glslang::EOpSubgroupQuadSwapHorizontal:
6585 case glslang::EOpSubgroupQuadSwapVertical:
6586 case glslang::EOpSubgroupQuadSwapDiagonal:
6587 builder.addCapability(spv::CapabilityGroupNonUniform);
6588 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6589 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006590#ifdef NV_EXTENSIONS
6591 case glslang::EOpSubgroupPartitionedAdd:
6592 case glslang::EOpSubgroupPartitionedMul:
6593 case glslang::EOpSubgroupPartitionedMin:
6594 case glslang::EOpSubgroupPartitionedMax:
6595 case glslang::EOpSubgroupPartitionedAnd:
6596 case glslang::EOpSubgroupPartitionedOr:
6597 case glslang::EOpSubgroupPartitionedXor:
6598 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6599 case glslang::EOpSubgroupPartitionedInclusiveMul:
6600 case glslang::EOpSubgroupPartitionedInclusiveMin:
6601 case glslang::EOpSubgroupPartitionedInclusiveMax:
6602 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6603 case glslang::EOpSubgroupPartitionedInclusiveOr:
6604 case glslang::EOpSubgroupPartitionedInclusiveXor:
6605 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6606 case glslang::EOpSubgroupPartitionedExclusiveMul:
6607 case glslang::EOpSubgroupPartitionedExclusiveMin:
6608 case glslang::EOpSubgroupPartitionedExclusiveMax:
6609 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6610 case glslang::EOpSubgroupPartitionedExclusiveOr:
6611 case glslang::EOpSubgroupPartitionedExclusiveXor:
6612 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6613 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6614 break;
6615#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006616 default: assert(0 && "Unhandled subgroup operation!");
6617 }
6618
6619 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6620 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6621 const bool isBool = typeProxy == glslang::EbtBool;
6622
6623 spv::Op opCode = spv::OpNop;
6624
6625 // Figure out which opcode to use.
6626 switch (op) {
6627 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6628 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6629 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6630 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6631 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6632 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6633 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6634 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6635 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6636 case glslang::EOpSubgroupBallotBitCount:
6637 case glslang::EOpSubgroupBallotInclusiveBitCount:
6638 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6639 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6640 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6641 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6642 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6643 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6644 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6645 case glslang::EOpSubgroupAdd:
6646 case glslang::EOpSubgroupInclusiveAdd:
6647 case glslang::EOpSubgroupExclusiveAdd:
6648 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006649#ifdef NV_EXTENSIONS
6650 case glslang::EOpSubgroupPartitionedAdd:
6651 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6652 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6653#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006654 if (isFloat) {
6655 opCode = spv::OpGroupNonUniformFAdd;
6656 } else {
6657 opCode = spv::OpGroupNonUniformIAdd;
6658 }
6659 break;
6660 case glslang::EOpSubgroupMul:
6661 case glslang::EOpSubgroupInclusiveMul:
6662 case glslang::EOpSubgroupExclusiveMul:
6663 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006664#ifdef NV_EXTENSIONS
6665 case glslang::EOpSubgroupPartitionedMul:
6666 case glslang::EOpSubgroupPartitionedInclusiveMul:
6667 case glslang::EOpSubgroupPartitionedExclusiveMul:
6668#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006669 if (isFloat) {
6670 opCode = spv::OpGroupNonUniformFMul;
6671 } else {
6672 opCode = spv::OpGroupNonUniformIMul;
6673 }
6674 break;
6675 case glslang::EOpSubgroupMin:
6676 case glslang::EOpSubgroupInclusiveMin:
6677 case glslang::EOpSubgroupExclusiveMin:
6678 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006679#ifdef NV_EXTENSIONS
6680 case glslang::EOpSubgroupPartitionedMin:
6681 case glslang::EOpSubgroupPartitionedInclusiveMin:
6682 case glslang::EOpSubgroupPartitionedExclusiveMin:
6683#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006684 if (isFloat) {
6685 opCode = spv::OpGroupNonUniformFMin;
6686 } else if (isUnsigned) {
6687 opCode = spv::OpGroupNonUniformUMin;
6688 } else {
6689 opCode = spv::OpGroupNonUniformSMin;
6690 }
6691 break;
6692 case glslang::EOpSubgroupMax:
6693 case glslang::EOpSubgroupInclusiveMax:
6694 case glslang::EOpSubgroupExclusiveMax:
6695 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006696#ifdef NV_EXTENSIONS
6697 case glslang::EOpSubgroupPartitionedMax:
6698 case glslang::EOpSubgroupPartitionedInclusiveMax:
6699 case glslang::EOpSubgroupPartitionedExclusiveMax:
6700#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006701 if (isFloat) {
6702 opCode = spv::OpGroupNonUniformFMax;
6703 } else if (isUnsigned) {
6704 opCode = spv::OpGroupNonUniformUMax;
6705 } else {
6706 opCode = spv::OpGroupNonUniformSMax;
6707 }
6708 break;
6709 case glslang::EOpSubgroupAnd:
6710 case glslang::EOpSubgroupInclusiveAnd:
6711 case glslang::EOpSubgroupExclusiveAnd:
6712 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006713#ifdef NV_EXTENSIONS
6714 case glslang::EOpSubgroupPartitionedAnd:
6715 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6716 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6717#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006718 if (isBool) {
6719 opCode = spv::OpGroupNonUniformLogicalAnd;
6720 } else {
6721 opCode = spv::OpGroupNonUniformBitwiseAnd;
6722 }
6723 break;
6724 case glslang::EOpSubgroupOr:
6725 case glslang::EOpSubgroupInclusiveOr:
6726 case glslang::EOpSubgroupExclusiveOr:
6727 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006728#ifdef NV_EXTENSIONS
6729 case glslang::EOpSubgroupPartitionedOr:
6730 case glslang::EOpSubgroupPartitionedInclusiveOr:
6731 case glslang::EOpSubgroupPartitionedExclusiveOr:
6732#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006733 if (isBool) {
6734 opCode = spv::OpGroupNonUniformLogicalOr;
6735 } else {
6736 opCode = spv::OpGroupNonUniformBitwiseOr;
6737 }
6738 break;
6739 case glslang::EOpSubgroupXor:
6740 case glslang::EOpSubgroupInclusiveXor:
6741 case glslang::EOpSubgroupExclusiveXor:
6742 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006743#ifdef NV_EXTENSIONS
6744 case glslang::EOpSubgroupPartitionedXor:
6745 case glslang::EOpSubgroupPartitionedInclusiveXor:
6746 case glslang::EOpSubgroupPartitionedExclusiveXor:
6747#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006748 if (isBool) {
6749 opCode = spv::OpGroupNonUniformLogicalXor;
6750 } else {
6751 opCode = spv::OpGroupNonUniformBitwiseXor;
6752 }
6753 break;
6754 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6755 case glslang::EOpSubgroupQuadSwapHorizontal:
6756 case glslang::EOpSubgroupQuadSwapVertical:
6757 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6758 default: assert(0 && "Unhandled subgroup operation!");
6759 }
6760
John Kessenich149afc32018-08-14 13:31:43 -06006761 // get the right Group Operation
6762 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006763 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006764 default:
6765 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006766 case glslang::EOpSubgroupBallotBitCount:
6767 case glslang::EOpSubgroupAdd:
6768 case glslang::EOpSubgroupMul:
6769 case glslang::EOpSubgroupMin:
6770 case glslang::EOpSubgroupMax:
6771 case glslang::EOpSubgroupAnd:
6772 case glslang::EOpSubgroupOr:
6773 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006774 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006775 break;
6776 case glslang::EOpSubgroupBallotInclusiveBitCount:
6777 case glslang::EOpSubgroupInclusiveAdd:
6778 case glslang::EOpSubgroupInclusiveMul:
6779 case glslang::EOpSubgroupInclusiveMin:
6780 case glslang::EOpSubgroupInclusiveMax:
6781 case glslang::EOpSubgroupInclusiveAnd:
6782 case glslang::EOpSubgroupInclusiveOr:
6783 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006784 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006785 break;
6786 case glslang::EOpSubgroupBallotExclusiveBitCount:
6787 case glslang::EOpSubgroupExclusiveAdd:
6788 case glslang::EOpSubgroupExclusiveMul:
6789 case glslang::EOpSubgroupExclusiveMin:
6790 case glslang::EOpSubgroupExclusiveMax:
6791 case glslang::EOpSubgroupExclusiveAnd:
6792 case glslang::EOpSubgroupExclusiveOr:
6793 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006794 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006795 break;
6796 case glslang::EOpSubgroupClusteredAdd:
6797 case glslang::EOpSubgroupClusteredMul:
6798 case glslang::EOpSubgroupClusteredMin:
6799 case glslang::EOpSubgroupClusteredMax:
6800 case glslang::EOpSubgroupClusteredAnd:
6801 case glslang::EOpSubgroupClusteredOr:
6802 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006803 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006804 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006805#ifdef NV_EXTENSIONS
6806 case glslang::EOpSubgroupPartitionedAdd:
6807 case glslang::EOpSubgroupPartitionedMul:
6808 case glslang::EOpSubgroupPartitionedMin:
6809 case glslang::EOpSubgroupPartitionedMax:
6810 case glslang::EOpSubgroupPartitionedAnd:
6811 case glslang::EOpSubgroupPartitionedOr:
6812 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006813 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006814 break;
6815 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6816 case glslang::EOpSubgroupPartitionedInclusiveMul:
6817 case glslang::EOpSubgroupPartitionedInclusiveMin:
6818 case glslang::EOpSubgroupPartitionedInclusiveMax:
6819 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6820 case glslang::EOpSubgroupPartitionedInclusiveOr:
6821 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006822 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006823 break;
6824 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6825 case glslang::EOpSubgroupPartitionedExclusiveMul:
6826 case glslang::EOpSubgroupPartitionedExclusiveMin:
6827 case glslang::EOpSubgroupPartitionedExclusiveMax:
6828 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6829 case glslang::EOpSubgroupPartitionedExclusiveOr:
6830 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006831 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006832 break;
6833#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006834 }
6835
John Kessenich149afc32018-08-14 13:31:43 -06006836 // build the instruction
6837 std::vector<spv::IdImmediate> spvGroupOperands;
6838
6839 // Every operation begins with the Execution Scope operand.
6840 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6841 spvGroupOperands.push_back(executionScope);
6842
6843 // Next, for all operations that use a Group Operation, push that as an operand.
6844 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006845 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006846 spvGroupOperands.push_back(groupOperand);
6847 }
6848
John Kessenich66011cb2018-03-06 16:12:04 -07006849 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006850 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6851 spv::IdImmediate operand = { true, *opIt };
6852 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006853 }
6854
6855 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006856 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006857 switch (op) {
6858 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006859 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6860 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6861 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6862 }
6863 if (directionId != spv::NoResult) {
6864 spv::IdImmediate direction = { true, directionId };
6865 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006866 }
6867
6868 return builder.createOp(opCode, typeId, spvGroupOperands);
6869}
6870
John Kessenich5e4b1242015-08-06 22:53:06 -06006871spv::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 -06006872{
John Kessenich66011cb2018-03-06 16:12:04 -07006873 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6874 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006875
John Kessenich140f3df2015-06-26 16:58:36 -06006876 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006877 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006878 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006879 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006880 spv::Id typeId0 = 0;
6881 if (consumedOperands > 0)
6882 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006883 spv::Id typeId1 = 0;
6884 if (consumedOperands > 1)
6885 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006886 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006887
6888 switch (op) {
6889 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006890 if (isFloat)
6891 libCall = spv::GLSLstd450FMin;
6892 else if (isUnsigned)
6893 libCall = spv::GLSLstd450UMin;
6894 else
6895 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006896 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006897 break;
6898 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006899 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006900 break;
6901 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006902 if (isFloat)
6903 libCall = spv::GLSLstd450FMax;
6904 else if (isUnsigned)
6905 libCall = spv::GLSLstd450UMax;
6906 else
6907 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006908 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006909 break;
6910 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006911 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006912 break;
6913 case glslang::EOpDot:
6914 opCode = spv::OpDot;
6915 break;
6916 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006917 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006918 break;
6919
6920 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006921 if (isFloat)
6922 libCall = spv::GLSLstd450FClamp;
6923 else if (isUnsigned)
6924 libCall = spv::GLSLstd450UClamp;
6925 else
6926 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006927 builder.promoteScalar(precision, operands.front(), operands[1]);
6928 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006929 break;
6930 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006931 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6932 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006933 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006934 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006935 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006936 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006937 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006938 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006939 break;
6940 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006941 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006942 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006943 break;
6944 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006945 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006946 builder.promoteScalar(precision, operands[0], operands[2]);
6947 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006948 break;
6949
6950 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006951 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006952 break;
6953 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006954 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006955 break;
6956 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006957 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006958 break;
6959 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006960 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006961 break;
6962 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006963 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006964 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006965 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006966#ifdef AMD_EXTENSIONS
6967 if (typeProxy == glslang::EbtFloat16)
6968 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6969#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006970 libCall = spv::GLSLstd450InterpolateAtSample;
6971 break;
6972 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006973#ifdef AMD_EXTENSIONS
6974 if (typeProxy == glslang::EbtFloat16)
6975 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6976#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006977 libCall = spv::GLSLstd450InterpolateAtOffset;
6978 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006979 case glslang::EOpAddCarry:
6980 opCode = spv::OpIAddCarry;
6981 typeId = builder.makeStructResultType(typeId0, typeId0);
6982 consumedOperands = 2;
6983 break;
6984 case glslang::EOpSubBorrow:
6985 opCode = spv::OpISubBorrow;
6986 typeId = builder.makeStructResultType(typeId0, typeId0);
6987 consumedOperands = 2;
6988 break;
6989 case glslang::EOpUMulExtended:
6990 opCode = spv::OpUMulExtended;
6991 typeId = builder.makeStructResultType(typeId0, typeId0);
6992 consumedOperands = 2;
6993 break;
6994 case glslang::EOpIMulExtended:
6995 opCode = spv::OpSMulExtended;
6996 typeId = builder.makeStructResultType(typeId0, typeId0);
6997 consumedOperands = 2;
6998 break;
6999 case glslang::EOpBitfieldExtract:
7000 if (isUnsigned)
7001 opCode = spv::OpBitFieldUExtract;
7002 else
7003 opCode = spv::OpBitFieldSExtract;
7004 break;
7005 case glslang::EOpBitfieldInsert:
7006 opCode = spv::OpBitFieldInsert;
7007 break;
7008
7009 case glslang::EOpFma:
7010 libCall = spv::GLSLstd450Fma;
7011 break;
7012 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007013 {
7014 libCall = spv::GLSLstd450FrexpStruct;
7015 assert(builder.isPointerType(typeId1));
7016 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007017 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007018#ifdef AMD_EXTENSIONS
7019 if (width == 16)
7020 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7021 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7022#endif
Rex Xu470026f2017-03-29 17:12:40 +08007023 if (builder.getNumComponents(operands[0]) == 1)
7024 frexpIntType = builder.makeIntegerType(width, true);
7025 else
7026 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7027 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7028 consumedOperands = 1;
7029 }
John Kessenich55e7d112015-11-15 21:33:39 -07007030 break;
7031 case glslang::EOpLdexp:
7032 libCall = spv::GLSLstd450Ldexp;
7033 break;
7034
Rex Xu574ab042016-04-14 16:53:07 +08007035 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007036 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007037
John Kessenich66011cb2018-03-06 16:12:04 -07007038 case glslang::EOpSubgroupBroadcast:
7039 case glslang::EOpSubgroupBallotBitExtract:
7040 case glslang::EOpSubgroupShuffle:
7041 case glslang::EOpSubgroupShuffleXor:
7042 case glslang::EOpSubgroupShuffleUp:
7043 case glslang::EOpSubgroupShuffleDown:
7044 case glslang::EOpSubgroupClusteredAdd:
7045 case glslang::EOpSubgroupClusteredMul:
7046 case glslang::EOpSubgroupClusteredMin:
7047 case glslang::EOpSubgroupClusteredMax:
7048 case glslang::EOpSubgroupClusteredAnd:
7049 case glslang::EOpSubgroupClusteredOr:
7050 case glslang::EOpSubgroupClusteredXor:
7051 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007052#ifdef NV_EXTENSIONS
7053 case glslang::EOpSubgroupPartitionedAdd:
7054 case glslang::EOpSubgroupPartitionedMul:
7055 case glslang::EOpSubgroupPartitionedMin:
7056 case glslang::EOpSubgroupPartitionedMax:
7057 case glslang::EOpSubgroupPartitionedAnd:
7058 case glslang::EOpSubgroupPartitionedOr:
7059 case glslang::EOpSubgroupPartitionedXor:
7060 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7061 case glslang::EOpSubgroupPartitionedInclusiveMul:
7062 case glslang::EOpSubgroupPartitionedInclusiveMin:
7063 case glslang::EOpSubgroupPartitionedInclusiveMax:
7064 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7065 case glslang::EOpSubgroupPartitionedInclusiveOr:
7066 case glslang::EOpSubgroupPartitionedInclusiveXor:
7067 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7068 case glslang::EOpSubgroupPartitionedExclusiveMul:
7069 case glslang::EOpSubgroupPartitionedExclusiveMin:
7070 case glslang::EOpSubgroupPartitionedExclusiveMax:
7071 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7072 case glslang::EOpSubgroupPartitionedExclusiveOr:
7073 case glslang::EOpSubgroupPartitionedExclusiveXor:
7074#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007075 return createSubgroupOperation(op, typeId, operands, typeProxy);
7076
Rex Xu9d93a232016-05-05 12:30:44 +08007077#ifdef AMD_EXTENSIONS
7078 case glslang::EOpSwizzleInvocations:
7079 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7080 libCall = spv::SwizzleInvocationsAMD;
7081 break;
7082 case glslang::EOpSwizzleInvocationsMasked:
7083 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7084 libCall = spv::SwizzleInvocationsMaskedAMD;
7085 break;
7086 case glslang::EOpWriteInvocation:
7087 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7088 libCall = spv::WriteInvocationAMD;
7089 break;
7090
7091 case glslang::EOpMin3:
7092 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7093 if (isFloat)
7094 libCall = spv::FMin3AMD;
7095 else {
7096 if (isUnsigned)
7097 libCall = spv::UMin3AMD;
7098 else
7099 libCall = spv::SMin3AMD;
7100 }
7101 break;
7102 case glslang::EOpMax3:
7103 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7104 if (isFloat)
7105 libCall = spv::FMax3AMD;
7106 else {
7107 if (isUnsigned)
7108 libCall = spv::UMax3AMD;
7109 else
7110 libCall = spv::SMax3AMD;
7111 }
7112 break;
7113 case glslang::EOpMid3:
7114 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7115 if (isFloat)
7116 libCall = spv::FMid3AMD;
7117 else {
7118 if (isUnsigned)
7119 libCall = spv::UMid3AMD;
7120 else
7121 libCall = spv::SMid3AMD;
7122 }
7123 break;
7124
7125 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007126 if (typeProxy == glslang::EbtFloat16)
7127 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007128 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7129 libCall = spv::InterpolateAtVertexAMD;
7130 break;
7131#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007132 case glslang::EOpBarrier:
7133 {
7134 // This is for the extended controlBarrier function, with four operands.
7135 // The unextended barrier() goes through createNoArgOperation.
7136 assert(operands.size() == 4);
7137 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7138 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7139 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7140 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7141 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7142 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7143 }
7144 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7145 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7146 }
7147 return 0;
7148 }
7149 break;
7150 case glslang::EOpMemoryBarrier:
7151 {
7152 // This is for the extended memoryBarrier function, with three operands.
7153 // The unextended memoryBarrier() goes through createNoArgOperation.
7154 assert(operands.size() == 3);
7155 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7156 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7157 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7158 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7159 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7160 }
7161 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7162 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7163 }
7164 return 0;
7165 }
7166 break;
Chao Chen3c366992018-09-19 11:41:59 -07007167
7168#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007169 case glslang::EOpReportIntersectionNV:
7170 {
7171 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007172 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007173 }
7174 break;
7175 case glslang::EOpTraceNV:
7176 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007177 builder.createNoResultOp(spv::OpTraceNV, operands);
7178 return 0;
7179 }
7180 break;
7181 case glslang::EOpExecuteCallableNV:
7182 {
7183 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007184 return 0;
7185 }
7186 break;
Chao Chen3c366992018-09-19 11:41:59 -07007187 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7188 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7189 return 0;
7190#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007191 case glslang::EOpCooperativeMatrixMulAdd:
7192 opCode = spv::OpCooperativeMatrixMulAddNV;
7193 break;
7194
John Kessenich140f3df2015-06-26 16:58:36 -06007195 default:
7196 return 0;
7197 }
7198
7199 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007200 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007201 // Use an extended instruction from the standard library.
7202 // Construct the call arguments, without modifying the original operands vector.
7203 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7204 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007205 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007206 } else if (opCode == spv::OpDot && !isFloat) {
7207 // int dot(int, int)
7208 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7209 const int componentCount = builder.getNumComponents(operands[0]);
7210 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7211 builder.setPrecision(mulOp, precision);
7212 id = builder.createCompositeExtract(mulOp, typeId, 0);
7213 for (int i = 1; i < componentCount; ++i) {
7214 builder.setPrecision(id, precision);
7215 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7216 }
John Kessenich2359bd02015-12-06 19:29:11 -07007217 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007218 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007219 case 0:
7220 // should all be handled by visitAggregate and createNoArgOperation
7221 assert(0);
7222 return 0;
7223 case 1:
7224 // should all be handled by createUnaryOperation
7225 assert(0);
7226 return 0;
7227 case 2:
7228 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7229 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007230 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007231 // anything 3 or over doesn't have l-value operands, so all should be consumed
7232 assert(consumedOperands == operands.size());
7233 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007234 break;
7235 }
7236 }
7237
John Kessenich55e7d112015-11-15 21:33:39 -07007238 // Decode the return types that were structures
7239 switch (op) {
7240 case glslang::EOpAddCarry:
7241 case glslang::EOpSubBorrow:
7242 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7243 id = builder.createCompositeExtract(id, typeId0, 0);
7244 break;
7245 case glslang::EOpUMulExtended:
7246 case glslang::EOpIMulExtended:
7247 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7248 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7249 break;
7250 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007251 {
7252 assert(operands.size() == 2);
7253 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7254 // "exp" is floating-point type (from HLSL intrinsic)
7255 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7256 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7257 builder.createStore(member1, operands[1]);
7258 } else
7259 // "exp" is integer type (from GLSL built-in function)
7260 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7261 id = builder.createCompositeExtract(id, typeId0, 0);
7262 }
John Kessenich55e7d112015-11-15 21:33:39 -07007263 break;
7264 default:
7265 break;
7266 }
7267
John Kessenich32cfd492016-02-02 12:37:46 -07007268 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007269}
7270
Rex Xu9d93a232016-05-05 12:30:44 +08007271// Intrinsics with no arguments (or no return value, and no precision).
7272spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007273{
Jeff Bolz36831c92018-09-05 10:11:41 -05007274 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7275 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007276
7277 switch (op) {
7278 case glslang::EOpEmitVertex:
7279 builder.createNoResultOp(spv::OpEmitVertex);
7280 return 0;
7281 case glslang::EOpEndPrimitive:
7282 builder.createNoResultOp(spv::OpEndPrimitive);
7283 return 0;
7284 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007285 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007286 if (glslangIntermediate->usingVulkanMemoryModel()) {
7287 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7288 spv::MemorySemanticsOutputMemoryKHRMask |
7289 spv::MemorySemanticsAcquireReleaseMask);
7290 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7291 } else {
7292 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7293 }
John Kessenich82979362017-12-11 04:02:24 -07007294 } else {
7295 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7296 spv::MemorySemanticsWorkgroupMemoryMask |
7297 spv::MemorySemanticsAcquireReleaseMask);
7298 }
John Kessenich140f3df2015-06-26 16:58:36 -06007299 return 0;
7300 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007301 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7302 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007303 return 0;
7304 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007305 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7306 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007307 return 0;
7308 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007309 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7310 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007311 return 0;
7312 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007313 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7314 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007315 return 0;
7316 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007317 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7318 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007319 return 0;
7320 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007321 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7322 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007323 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007324 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007325 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007326 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007327 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007328 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007329 case glslang::EOpDeviceMemoryBarrier:
7330 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7331 spv::MemorySemanticsImageMemoryMask |
7332 spv::MemorySemanticsAcquireReleaseMask);
7333 return 0;
7334 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7335 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7336 spv::MemorySemanticsImageMemoryMask |
7337 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007338 return 0;
7339 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007340 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7341 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007342 return 0;
7343 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007344 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7345 spv::MemorySemanticsWorkgroupMemoryMask |
7346 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007347 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007348 case glslang::EOpSubgroupBarrier:
7349 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7350 spv::MemorySemanticsAcquireReleaseMask);
7351 return spv::NoResult;
7352 case glslang::EOpSubgroupMemoryBarrier:
7353 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7354 spv::MemorySemanticsAcquireReleaseMask);
7355 return spv::NoResult;
7356 case glslang::EOpSubgroupMemoryBarrierBuffer:
7357 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7358 spv::MemorySemanticsAcquireReleaseMask);
7359 return spv::NoResult;
7360 case glslang::EOpSubgroupMemoryBarrierImage:
7361 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7362 spv::MemorySemanticsAcquireReleaseMask);
7363 return spv::NoResult;
7364 case glslang::EOpSubgroupMemoryBarrierShared:
7365 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7366 spv::MemorySemanticsAcquireReleaseMask);
7367 return spv::NoResult;
7368 case glslang::EOpSubgroupElect: {
7369 std::vector<spv::Id> operands;
7370 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7371 }
Rex Xu9d93a232016-05-05 12:30:44 +08007372#ifdef AMD_EXTENSIONS
7373 case glslang::EOpTime:
7374 {
7375 std::vector<spv::Id> args; // Dummy arguments
7376 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7377 return builder.setPrecision(id, precision);
7378 }
7379#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007380#ifdef NV_EXTENSIONS
7381 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007382 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007383 return 0;
7384 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007385 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007386 return 0;
7387#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007388 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007389 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007390 return 0;
7391 }
7392}
7393
7394spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7395{
John Kessenich2f273362015-07-18 22:34:27 -06007396 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007397 spv::Id id;
7398 if (symbolValues.end() != iter) {
7399 id = iter->second;
7400 return id;
7401 }
7402
7403 // it was not found, create it
7404 id = createSpvVariable(symbol);
7405 symbolValues[symbol->getId()] = id;
7406
Rex Xuc884b4a2016-06-29 15:03:44 +08007407 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007408 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7409 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7410 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007411#ifdef NV_EXTENSIONS
7412 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7413#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007414 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007415 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007416 if (symbol->getQualifier().hasIndex())
7417 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7418 if (symbol->getQualifier().hasComponent())
7419 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007420 // atomic counters use this:
7421 if (symbol->getQualifier().hasOffset())
7422 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007423 }
7424
scygan2c864272016-05-18 18:09:17 +02007425 if (symbol->getQualifier().hasLocation())
7426 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007427 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007428 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007429 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007430 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007431 }
John Kessenich140f3df2015-06-26 16:58:36 -06007432 if (symbol->getQualifier().hasSet())
7433 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007434 else if (IsDescriptorResource(symbol->getType())) {
7435 // default to 0
7436 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7437 }
John Kessenich140f3df2015-06-26 16:58:36 -06007438 if (symbol->getQualifier().hasBinding())
7439 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007440 else if (IsDescriptorResource(symbol->getType())) {
7441 // default to 0
7442 builder.addDecoration(id, spv::DecorationBinding, 0);
7443 }
John Kessenich6c292d32016-02-15 20:58:50 -07007444 if (symbol->getQualifier().hasAttachment())
7445 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007446 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007448 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007449 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007450 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7451 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7452 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7453 }
7454 if (symbol->getQualifier().hasXfbOffset())
7455 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007456 }
7457
Rex Xu1da878f2016-02-21 20:59:01 +08007458 if (symbol->getType().isImage()) {
7459 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007460 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007461 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007462 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007463 }
7464
John Kessenich140f3df2015-06-26 16:58:36 -06007465 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007466 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007467 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007468 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007469
John Kessenich5611c6d2018-04-05 11:25:02 -06007470 // nonuniform
7471 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7472
John Kessenichecba76f2017-01-06 00:34:48 -07007473#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007474 if (builtIn == spv::BuiltInSampleMask) {
7475 spv::Decoration decoration;
7476 // GL_NV_sample_mask_override_coverage extension
7477 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007478 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007479 else
7480 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007481 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007482 if (decoration != spv::DecorationMax) {
7483 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7484 }
7485 }
chaoc771d89f2017-01-13 01:10:53 -08007486 else if (builtIn == spv::BuiltInLayer) {
7487 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007488 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007489 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007490 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7491 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7492 }
John Kessenichb41bff62017-08-11 13:07:17 -06007493 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007494 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7495 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007496 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7497 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7498 }
7499 }
7500
chaoc6e5acae2016-12-20 13:28:52 -08007501 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007502 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007503 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007504 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7505 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007506 if (symbol->getQualifier().pervertexNV) {
7507 builder.addDecoration(id, spv::DecorationPerVertexNV);
7508 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7509 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7510 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007511#endif
7512
John Kessenich5d610ee2018-03-07 18:05:55 -07007513 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7514 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7515 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7516 symbol->getType().getQualifier().semanticName);
7517 }
7518
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007519 if (symbol->getBasicType() == glslang::EbtReference) {
7520 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7521 }
7522
John Kessenich140f3df2015-06-26 16:58:36 -06007523 return id;
7524}
7525
Chao Chen3c366992018-09-19 11:41:59 -07007526#ifdef NV_EXTENSIONS
7527// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7528void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7529{
7530 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007531 if (qualifier.perPrimitiveNV) {
7532 // Need to add capability/extension for fragment shader.
7533 // Mesh shader already adds this by default.
7534 if (glslangIntermediate->getStage() == EShLangFragment) {
7535 builder.addCapability(spv::CapabilityMeshShadingNV);
7536 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7537 }
Chao Chen3c366992018-09-19 11:41:59 -07007538 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007539 }
Chao Chen3c366992018-09-19 11:41:59 -07007540 if (qualifier.perViewNV)
7541 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7542 if (qualifier.perTaskNV)
7543 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7544 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007545 if (qualifier.perPrimitiveNV) {
7546 // Need to add capability/extension for fragment shader.
7547 // Mesh shader already adds this by default.
7548 if (glslangIntermediate->getStage() == EShLangFragment) {
7549 builder.addCapability(spv::CapabilityMeshShadingNV);
7550 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7551 }
Chao Chen3c366992018-09-19 11:41:59 -07007552 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007553 }
Chao Chen3c366992018-09-19 11:41:59 -07007554 if (qualifier.perViewNV)
7555 builder.addDecoration(id, spv::DecorationPerViewNV);
7556 if (qualifier.perTaskNV)
7557 builder.addDecoration(id, spv::DecorationPerTaskNV);
7558 }
7559}
7560#endif
7561
John Kessenich55e7d112015-11-15 21:33:39 -07007562// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007563// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007564//
7565// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7566//
7567// Recursively walk the nodes. The nodes form a tree whose leaves are
7568// regular constants, which themselves are trees that createSpvConstant()
7569// recursively walks. So, this function walks the "top" of the tree:
7570// - emit specialization constant-building instructions for specConstant
7571// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007572spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007573{
John Kessenich7cc0e282016-03-20 00:46:02 -06007574 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007575
qining4f4bb812016-04-03 23:55:17 -04007576 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007577 if (! node.getQualifier().specConstant) {
7578 // hand off to the non-spec-constant path
7579 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7580 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007581 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007582 nextConst, false);
7583 }
7584
7585 // We now know we have a specialization constant to build
7586
John Kessenichd94c0032016-05-30 19:29:40 -06007587 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007588 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7589 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7590 std::vector<spv::Id> dimConstId;
7591 for (int dim = 0; dim < 3; ++dim) {
7592 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7593 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007594 if (specConst) {
7595 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7596 glslangIntermediate->getLocalSizeSpecId(dim));
7597 }
qining4f4bb812016-04-03 23:55:17 -04007598 }
7599 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7600 }
7601
7602 // An AST node labelled as specialization constant should be a symbol node.
7603 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7604 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007605 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007606 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007607 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7608 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7609 // will set the builder into spec constant op instruction generating mode.
7610 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007611 result = accessChainLoad(sub_tree->getType());
7612 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007613 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007614 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007615 } else {
7616 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007617 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007618 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007619 builder.addName(result, sn->getName().c_str());
7620 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007621 }
qining4f4bb812016-04-03 23:55:17 -04007622
7623 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7624 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007625 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007626 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007627}
7628
John Kessenich140f3df2015-06-26 16:58:36 -06007629// Use 'consts' as the flattened glslang source of scalar constants to recursively
7630// build the aggregate SPIR-V constant.
7631//
7632// If there are not enough elements present in 'consts', 0 will be substituted;
7633// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7634//
qining08408382016-03-21 09:51:37 -04007635spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007636{
7637 // vector of constants for SPIR-V
7638 std::vector<spv::Id> spvConsts;
7639
7640 // Type is used for struct and array constants
7641 spv::Id typeId = convertGlslangToSpvType(glslangType);
7642
7643 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007644 glslang::TType elementType(glslangType, 0);
7645 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007646 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007647 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007648 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007649 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007650 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007651 } else if (glslangType.isCoopMat()) {
7652 glslang::TType componentType(glslangType.getBasicType());
7653 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007654 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007655 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7656 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007657 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007658 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007659 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7660 bool zero = nextConst >= consts.size();
7661 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007662 case glslang::EbtInt8:
7663 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7664 break;
7665 case glslang::EbtUint8:
7666 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7667 break;
7668 case glslang::EbtInt16:
7669 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7670 break;
7671 case glslang::EbtUint16:
7672 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7673 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007674 case glslang::EbtInt:
7675 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7676 break;
7677 case glslang::EbtUint:
7678 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7679 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007680 case glslang::EbtInt64:
7681 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7682 break;
7683 case glslang::EbtUint64:
7684 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7685 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007686 case glslang::EbtFloat:
7687 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7688 break;
7689 case glslang::EbtDouble:
7690 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7691 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007692 case glslang::EbtFloat16:
7693 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7694 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007695 case glslang::EbtBool:
7696 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7697 break;
7698 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007699 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007700 break;
7701 }
7702 ++nextConst;
7703 }
7704 } else {
7705 // we have a non-aggregate (scalar) constant
7706 bool zero = nextConst >= consts.size();
7707 spv::Id scalar = 0;
7708 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007709 case glslang::EbtInt8:
7710 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7711 break;
7712 case glslang::EbtUint8:
7713 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7714 break;
7715 case glslang::EbtInt16:
7716 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7717 break;
7718 case glslang::EbtUint16:
7719 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7720 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007721 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007722 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007723 break;
7724 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007725 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007726 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007727 case glslang::EbtInt64:
7728 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7729 break;
7730 case glslang::EbtUint64:
7731 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7732 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007733 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007734 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007735 break;
7736 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007737 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007738 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007739 case glslang::EbtFloat16:
7740 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007742 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007743 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007744 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007745 case glslang::EbtReference:
7746 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7747 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7748 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007749 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007750 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007751 break;
7752 }
7753 ++nextConst;
7754 return scalar;
7755 }
7756
7757 return builder.makeCompositeConstant(typeId, spvConsts);
7758}
7759
John Kessenich7c1aa102015-10-15 13:29:11 -06007760// Return true if the node is a constant or symbol whose reading has no
7761// non-trivial observable cost or effect.
7762bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7763{
7764 // don't know what this is
7765 if (node == nullptr)
7766 return false;
7767
7768 // a constant is safe
7769 if (node->getAsConstantUnion() != nullptr)
7770 return true;
7771
7772 // not a symbol means non-trivial
7773 if (node->getAsSymbolNode() == nullptr)
7774 return false;
7775
7776 // a symbol, depends on what's being read
7777 switch (node->getType().getQualifier().storage) {
7778 case glslang::EvqTemporary:
7779 case glslang::EvqGlobal:
7780 case glslang::EvqIn:
7781 case glslang::EvqInOut:
7782 case glslang::EvqConst:
7783 case glslang::EvqConstReadOnly:
7784 case glslang::EvqUniform:
7785 return true;
7786 default:
7787 return false;
7788 }
qining25262b32016-05-06 17:25:16 -04007789}
John Kessenich7c1aa102015-10-15 13:29:11 -06007790
7791// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007792// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007793// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007794// Return true if trivial.
7795bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7796{
7797 if (node == nullptr)
7798 return false;
7799
John Kessenich84cc15f2017-05-24 16:44:47 -06007800 // count non scalars as trivial, as well as anything coming from HLSL
7801 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007802 return true;
7803
John Kessenich7c1aa102015-10-15 13:29:11 -06007804 // symbols and constants are trivial
7805 if (isTrivialLeaf(node))
7806 return true;
7807
7808 // otherwise, it needs to be a simple operation or one or two leaf nodes
7809
7810 // not a simple operation
7811 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7812 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7813 if (binaryNode == nullptr && unaryNode == nullptr)
7814 return false;
7815
7816 // not on leaf nodes
7817 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7818 return false;
7819
7820 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7821 return false;
7822 }
7823
7824 switch (node->getAsOperator()->getOp()) {
7825 case glslang::EOpLogicalNot:
7826 case glslang::EOpConvIntToBool:
7827 case glslang::EOpConvUintToBool:
7828 case glslang::EOpConvFloatToBool:
7829 case glslang::EOpConvDoubleToBool:
7830 case glslang::EOpEqual:
7831 case glslang::EOpNotEqual:
7832 case glslang::EOpLessThan:
7833 case glslang::EOpGreaterThan:
7834 case glslang::EOpLessThanEqual:
7835 case glslang::EOpGreaterThanEqual:
7836 case glslang::EOpIndexDirect:
7837 case glslang::EOpIndexDirectStruct:
7838 case glslang::EOpLogicalXor:
7839 case glslang::EOpAny:
7840 case glslang::EOpAll:
7841 return true;
7842 default:
7843 return false;
7844 }
7845}
7846
7847// Emit short-circuiting code, where 'right' is never evaluated unless
7848// the left side is true (for &&) or false (for ||).
7849spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7850{
7851 spv::Id boolTypeId = builder.makeBoolType();
7852
7853 // emit left operand
7854 builder.clearAccessChain();
7855 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007856 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007857
7858 // Operands to accumulate OpPhi operands
7859 std::vector<spv::Id> phiOperands;
7860 // accumulate left operand's phi information
7861 phiOperands.push_back(leftId);
7862 phiOperands.push_back(builder.getBuildPoint()->getId());
7863
7864 // Make the two kinds of operation symmetric with a "!"
7865 // || => emit "if (! left) result = right"
7866 // && => emit "if ( left) result = right"
7867 //
7868 // TODO: this runtime "not" for || could be avoided by adding functionality
7869 // to 'builder' to have an "else" without an "then"
7870 if (op == glslang::EOpLogicalOr)
7871 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7872
7873 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007874 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007875
7876 // emit right operand as the "then" part of the "if"
7877 builder.clearAccessChain();
7878 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007879 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007880
7881 // accumulate left operand's phi information
7882 phiOperands.push_back(rightId);
7883 phiOperands.push_back(builder.getBuildPoint()->getId());
7884
7885 // finish the "if"
7886 ifBuilder.makeEndIf();
7887
7888 // phi together the two results
7889 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7890}
7891
Frank Henigman541f7bb2018-01-16 00:18:26 -05007892#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007893// Return type Id of the imported set of extended instructions corresponds to the name.
7894// Import this set if it has not been imported yet.
7895spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7896{
7897 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7898 return extBuiltinMap[name];
7899 else {
Rex Xu51596642016-09-21 18:56:12 +08007900 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007901 spv::Id extBuiltins = builder.import(name);
7902 extBuiltinMap[name] = extBuiltins;
7903 return extBuiltins;
7904 }
7905}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007906#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007907
John Kessenich140f3df2015-06-26 16:58:36 -06007908}; // end anonymous namespace
7909
7910namespace glslang {
7911
John Kessenich68d78fd2015-07-12 19:28:10 -06007912void GetSpirvVersion(std::string& version)
7913{
John Kessenich9e55f632015-07-15 10:03:39 -06007914 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007915 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007916 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007917 version = buf;
7918}
7919
John Kessenicha372a3e2017-11-02 22:32:14 -06007920// For low-order part of the generator's magic number. Bump up
7921// when there is a change in the style (e.g., if SSA form changes,
7922// or a different instruction sequence to do something gets used).
7923int GetSpirvGeneratorVersion()
7924{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007925 // return 1; // start
7926 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007927 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007928 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007929 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007930 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7931 // versions 4 and 6 each generate OpArrayLength as it has long been done
7932 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007933}
7934
John Kessenich140f3df2015-06-26 16:58:36 -06007935// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007936void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007937{
7938 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007939 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007940 if (out.fail())
7941 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007942 for (int i = 0; i < (int)spirv.size(); ++i) {
7943 unsigned int word = spirv[i];
7944 out.write((const char*)&word, 4);
7945 }
7946 out.close();
7947}
7948
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007949// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007950void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007951{
7952 std::ofstream out;
7953 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007954 if (out.fail())
7955 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007956 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007957 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007958 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007959 if (varName != nullptr) {
7960 out << "\t #pragma once" << std::endl;
7961 out << "const uint32_t " << varName << "[] = {" << std::endl;
7962 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007963 const int WORDS_PER_LINE = 8;
7964 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7965 out << "\t";
7966 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7967 const unsigned int word = spirv[i + j];
7968 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7969 if (i + j + 1 < (int)spirv.size()) {
7970 out << ",";
7971 }
7972 }
7973 out << std::endl;
7974 }
Flavio15017db2017-02-15 14:29:33 -08007975 if (varName != nullptr) {
7976 out << "};";
7977 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007978 out.close();
7979}
7980
John Kessenich140f3df2015-06-26 16:58:36 -06007981//
7982// Set up the glslang traversal
7983//
John Kessenich4e11b612018-08-30 16:56:59 -06007984void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007985{
Lei Zhang17535f72016-05-04 15:55:59 -04007986 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007987 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007988}
7989
John Kessenich4e11b612018-08-30 16:56:59 -06007990void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007991 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007992{
John Kessenich140f3df2015-06-26 16:58:36 -06007993 TIntermNode* root = intermediate.getTreeRoot();
7994
7995 if (root == 0)
7996 return;
7997
John Kessenich4e11b612018-08-30 16:56:59 -06007998 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007999 if (options == nullptr)
8000 options = &defaultOptions;
8001
John Kessenich4e11b612018-08-30 16:56:59 -06008002 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008003
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008004 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008005 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008006 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008007 it.dumpSpv(spirv);
8008
GregFfb03a552018-03-29 11:49:14 -06008009#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008010 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8011 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008012 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008013 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008014
John Kessenich4e11b612018-08-30 16:56:59 -06008015 if (options->validate)
8016 SpirvToolsValidate(intermediate, spirv, logger);
8017
John Kessenich717c80a2018-08-23 15:17:10 -06008018 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008019 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008020
GregFcd1f1692017-09-21 18:40:22 -06008021#endif
8022
John Kessenich4e11b612018-08-30 16:56:59 -06008023 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008024}
8025
8026}; // end namespace glslang