blob: 4a5dc0b86f138c53e31283a481508c26571a7db5 [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 Kessenich9c14f772019-06-17 08:38:35 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 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);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
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,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500181 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600182 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);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
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 Kessenich9c14f772019-06-17 08:38:35 -0600211 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
212 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500213 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600214
John Kessenich121853f2017-05-31 17:11:16 -0600215 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600217 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700218 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600219 int sequenceDepth;
220
Lei Zhang17535f72016-05-04 15:55:59 -0400221 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400222
John Kessenich140f3df2015-06-26 16:58:36 -0600223 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
224 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700225 bool inEntryPoint;
226 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700227 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 -0700228 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600229 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600230 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600231 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800232 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600235 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600236 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700237 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
239 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700241 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600242 // Map pointee types for EbtReference to their forward pointers
243 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600244 // Type forcing, for when SPIR-V wants a different type than the AST,
245 // requiring local translation to and from SPIR-V type on every access.
246 // Maps <builtin-variable-id -> AST-required-type-id>
247 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600248};
249
250//
251// Helper functions for translating glslang representations to SPIR-V enumerants.
252//
253
254// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700255spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600256{
John Kessenich66e2faf2016-03-12 18:34:36 -0700257 switch (source) {
258 case glslang::EShSourceGlsl:
259 switch (profile) {
260 case ENoProfile:
261 case ECoreProfile:
262 case ECompatibilityProfile:
263 return spv::SourceLanguageGLSL;
264 case EEsProfile:
265 return spv::SourceLanguageESSL;
266 default:
267 return spv::SourceLanguageUnknown;
268 }
269 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600270 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 default:
272 return spv::SourceLanguageUnknown;
273 }
274}
275
276// Translate glslang language (stage) to SPIR-V execution model.
277spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
278{
279 switch (stage) {
280 case EShLangVertex: return spv::ExecutionModelVertex;
281 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
282 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
283 case EShLangGeometry: return spv::ExecutionModelGeometry;
284 case EShLangFragment: return spv::ExecutionModelFragment;
285 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700286#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700287 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
288 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
289 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
290 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
291 case EShLangMissNV: return spv::ExecutionModelMissNV;
292 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700293 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
294 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
295#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 return spv::ExecutionModelFragment;
299 }
300}
301
John Kessenich140f3df2015-06-26 16:58:36 -0600302// Translate glslang sampler type to SPIR-V dimensionality.
303spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
304{
305 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700306 case glslang::Esd1D: return spv::Dim1D;
307 case glslang::Esd2D: return spv::Dim2D;
308 case glslang::Esd3D: return spv::Dim3D;
309 case glslang::EsdCube: return spv::DimCube;
310 case glslang::EsdRect: return spv::DimRect;
311 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700312 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600313 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700314 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::Dim2D;
316 }
317}
318
John Kessenichf6640762016-08-01 19:44:00 -0600319// Translate glslang precision to SPIR-V precision decorations.
320spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600321{
John Kessenichf6640762016-08-01 19:44:00 -0600322 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700323 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600324 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600325 default:
326 return spv::NoPrecision;
327 }
328}
329
John Kessenichf6640762016-08-01 19:44:00 -0600330// Translate glslang type to SPIR-V precision decorations.
331spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
332{
333 return TranslatePrecisionDecoration(type.getQualifier().precision);
334}
335
John Kessenich140f3df2015-06-26 16:58:36 -0600336// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600337spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 if (type.getBasicType() == glslang::EbtBlock) {
340 switch (type.getQualifier().storage) {
341 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600342 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 case glslang::EvqVaryingIn: return spv::DecorationBlock;
344 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700345#ifdef NV_EXTENSIONS
346 case glslang::EvqPayloadNV: return spv::DecorationBlock;
347 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
348 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700349 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
350 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700351#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600352 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600354 break;
355 }
356 }
357
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359}
360
Rex Xu1da878f2016-02-21 20:59:01 +0800361// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500362void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800363{
Jeff Bolz36831c92018-09-05 10:11:41 -0500364 if (!useVulkanMemoryModel) {
365 if (qualifier.coherent)
366 memory.push_back(spv::DecorationCoherent);
367 if (qualifier.volatil) {
368 memory.push_back(spv::DecorationVolatile);
369 memory.push_back(spv::DecorationCoherent);
370 }
John Kessenich14b85d32018-06-04 15:36:03 -0600371 }
Rex Xu1da878f2016-02-21 20:59:01 +0800372 if (qualifier.restrict)
373 memory.push_back(spv::DecorationRestrict);
374 if (qualifier.readonly)
375 memory.push_back(spv::DecorationNonWritable);
376 if (qualifier.writeonly)
377 memory.push_back(spv::DecorationNonReadable);
378}
379
John Kessenich140f3df2015-06-26 16:58:36 -0600380// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700381spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600382{
383 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700384 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600385 case glslang::ElmRowMajor:
386 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700387 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700389 default:
390 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392 }
393 } else {
394 switch (type.getBasicType()) {
395 default:
John Kessenich4016e382016-07-15 11:53:56 -0600396 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 break;
398 case glslang::EbtBlock:
399 switch (type.getQualifier().storage) {
400 case glslang::EvqUniform:
401 case glslang::EvqBuffer:
402 switch (type.getQualifier().layoutPacking) {
403 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600404 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
405 default:
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 }
408 case glslang::EvqVaryingIn:
409 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700410 if (type.getQualifier().isTaskMemory()) {
411 switch (type.getQualifier().layoutPacking) {
412 case glslang::ElpShared: return spv::DecorationGLSLShared;
413 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
414 default: break;
415 }
416 } else {
417 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
418 }
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700420#ifdef NV_EXTENSIONS
421 case glslang::EvqPayloadNV:
422 case glslang::EvqPayloadInNV:
423 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700424 case glslang::EvqCallableDataNV:
425 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700426 return spv::DecorationMax;
427#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600428 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700429 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 }
432 }
433 }
434}
435
436// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600437// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700438// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800439spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600440{
Rex Xubbceed72016-05-21 09:40:44 +0800441 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700442 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800444 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700445 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700446 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600447 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800448#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800449 else if (qualifier.explicitInterp) {
450 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800451 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800452 }
Rex Xu9d93a232016-05-05 12:30:44 +0800453#endif
Rex Xubbceed72016-05-21 09:40:44 +0800454 else
John Kessenich4016e382016-07-15 11:53:56 -0600455 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800456}
457
458// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600459// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800460// should be applied.
461spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
462{
463 if (qualifier.patch)
464 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700465 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600466 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700467 else if (qualifier.sample) {
468 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600469 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700470 } else
John Kessenich4016e382016-07-15 11:53:56 -0600471 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600472}
473
John Kessenich92187592016-02-01 13:45:25 -0700474// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700475spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600476{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700477 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600478 return spv::DecorationInvariant;
479 else
John Kessenich4016e382016-07-15 11:53:56 -0600480 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600481}
482
qining9220dbb2016-05-04 17:34:38 -0400483// If glslang type is noContraction, return SPIR-V NoContraction decoration.
484spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
485{
486 if (qualifier.noContraction)
487 return spv::DecorationNoContraction;
488 else
John Kessenich4016e382016-07-15 11:53:56 -0600489 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400490}
491
John Kessenich5611c6d2018-04-05 11:25:02 -0600492// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
493spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
494{
495 if (qualifier.isNonUniform()) {
496 builder.addExtension("SPV_EXT_descriptor_indexing");
497 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
498 return spv::DecorationNonUniformEXT;
499 } else
500 return spv::DecorationMax;
501}
502
Jeff Bolz36831c92018-09-05 10:11:41 -0500503spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
504{
505 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
506 return spv::MemoryAccessMaskNone;
507 }
508 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
509 if (coherentFlags.volatil ||
510 coherentFlags.coherent ||
511 coherentFlags.devicecoherent ||
512 coherentFlags.queuefamilycoherent ||
513 coherentFlags.workgroupcoherent ||
514 coherentFlags.subgroupcoherent) {
515 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
516 spv::MemoryAccessMakePointerVisibleKHRMask;
517 }
518 if (coherentFlags.nonprivate) {
519 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
520 }
521 if (coherentFlags.volatil) {
522 mask = mask | spv::MemoryAccessVolatileMask;
523 }
524 if (mask != spv::MemoryAccessMaskNone) {
525 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
526 }
527 return mask;
528}
529
530spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
531{
532 if (!glslangIntermediate->usingVulkanMemoryModel()) {
533 return spv::ImageOperandsMaskNone;
534 }
535 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
536 if (coherentFlags.volatil ||
537 coherentFlags.coherent ||
538 coherentFlags.devicecoherent ||
539 coherentFlags.queuefamilycoherent ||
540 coherentFlags.workgroupcoherent ||
541 coherentFlags.subgroupcoherent) {
542 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
543 spv::ImageOperandsMakeTexelVisibleKHRMask;
544 }
545 if (coherentFlags.nonprivate) {
546 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
547 }
548 if (coherentFlags.volatil) {
549 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
550 }
551 if (mask != spv::ImageOperandsMaskNone) {
552 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
553 }
554 return mask;
555}
556
557spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
558{
559 spv::Builder::AccessChain::CoherentFlags flags;
560 flags.coherent = type.getQualifier().coherent;
561 flags.devicecoherent = type.getQualifier().devicecoherent;
562 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
563 // shared variables are implicitly workgroupcoherent in GLSL.
564 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
565 type.getQualifier().storage == glslang::EvqShared;
566 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600567 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 // *coherent variables are implicitly nonprivate in GLSL
569 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500570 flags.subgroupcoherent ||
571 flags.workgroupcoherent ||
572 flags.queuefamilycoherent ||
573 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600574 flags.coherent ||
575 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 flags.isImage = type.getBasicType() == glslang::EbtSampler;
577 return flags;
578}
579
580spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
581{
582 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600583 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500584 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
585 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
586 } else if (coherentFlags.devicecoherent) {
587 scope = spv::ScopeDevice;
588 } else if (coherentFlags.queuefamilycoherent) {
589 scope = spv::ScopeQueueFamilyKHR;
590 } else if (coherentFlags.workgroupcoherent) {
591 scope = spv::ScopeWorkgroup;
592 } else if (coherentFlags.subgroupcoherent) {
593 scope = spv::ScopeSubgroup;
594 } else {
595 scope = spv::ScopeMax;
596 }
597 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
598 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
599 }
600 return scope;
601}
602
David Netoa901ffe2016-06-08 14:11:40 +0100603// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
604// associated capabilities when required. For some built-in variables, a capability
605// is generated only when using the variable in an executable instruction, but not when
606// just declaring a struct member variable with it. This is true for PointSize,
607// ClipDistance, and CullDistance.
608spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600609{
610 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700611 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600612 // Defer adding the capability until the built-in is actually used.
613 if (! memberDeclaration) {
614 switch (glslangIntermediate->getStage()) {
615 case EShLangGeometry:
616 builder.addCapability(spv::CapabilityGeometryPointSize);
617 break;
618 case EShLangTessControl:
619 case EShLangTessEvaluation:
620 builder.addCapability(spv::CapabilityTessellationPointSize);
621 break;
622 default:
623 break;
624 }
John Kessenich92187592016-02-01 13:45:25 -0700625 }
626 return spv::BuiltInPointSize;
627
John Kessenichebb50532016-05-16 19:22:05 -0600628 // These *Distance capabilities logically belong here, but if the member is declared and
629 // then never used, consumers of SPIR-V prefer the capability not be declared.
630 // They are now generated when used, rather than here when declared.
631 // Potentially, the specification should be more clear what the minimum
632 // use needed is to trigger the capability.
633 //
John Kessenich92187592016-02-01 13:45:25 -0700634 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100635 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800636 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700637 return spv::BuiltInClipDistance;
638
639 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100640 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800641 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700642 return spv::BuiltInCullDistance;
643
644 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600645 builder.addCapability(spv::CapabilityMultiViewport);
646 if (glslangIntermediate->getStage() == EShLangVertex ||
647 glslangIntermediate->getStage() == EShLangTessControl ||
648 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800649
John Kessenichba6a3c22017-09-13 13:22:50 -0600650 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
651 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800652 }
John Kessenich92187592016-02-01 13:45:25 -0700653 return spv::BuiltInViewportIndex;
654
John Kessenich5e801132016-02-15 11:09:46 -0700655 case glslang::EbvSampleId:
656 builder.addCapability(spv::CapabilitySampleRateShading);
657 return spv::BuiltInSampleId;
658
659 case glslang::EbvSamplePosition:
660 builder.addCapability(spv::CapabilitySampleRateShading);
661 return spv::BuiltInSamplePosition;
662
663 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700664 return spv::BuiltInSampleMask;
665
John Kessenich78a45572016-07-08 14:05:15 -0600666 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700667#ifdef NV_EXTENSIONS
668 if (glslangIntermediate->getStage() == EShLangMeshNV) {
669 return spv::BuiltInLayer;
670 }
671#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600672 builder.addCapability(spv::CapabilityGeometry);
673 if (glslangIntermediate->getStage() == EShLangVertex ||
674 glslangIntermediate->getStage() == EShLangTessControl ||
675 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800676
John Kessenichba6a3c22017-09-13 13:22:50 -0600677 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
678 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800679 }
John Kessenich78a45572016-07-08 14:05:15 -0600680 return spv::BuiltInLayer;
681
John Kessenich140f3df2015-06-26 16:58:36 -0600682 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600683 case glslang::EbvVertexId: return spv::BuiltInVertexId;
684 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700685 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
686 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800687
John Kessenichda581a22015-10-14 14:10:30 -0600688 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700689 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800690 builder.addCapability(spv::CapabilityDrawParameters);
691 return spv::BuiltInBaseVertex;
692
John Kessenichda581a22015-10-14 14:10:30 -0600693 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700694 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800695 builder.addCapability(spv::CapabilityDrawParameters);
696 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200697
John Kessenichda581a22015-10-14 14:10:30 -0600698 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700699 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800700 builder.addCapability(spv::CapabilityDrawParameters);
701 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200702
703 case glslang::EbvPrimitiveId:
704 if (glslangIntermediate->getStage() == EShLangFragment)
705 builder.addCapability(spv::CapabilityGeometry);
706 return spv::BuiltInPrimitiveId;
707
Rex Xu37cdcee2017-06-29 17:46:34 +0800708 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800709 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
710 builder.addCapability(spv::CapabilityStencilExportEXT);
711 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800712
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
715 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
716 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
717 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
718 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
719 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
720 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600721 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
722 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
723 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
724 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
725 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
726 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
727 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
728 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800729
Rex Xu574ab042016-04-14 16:53:07 +0800730 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800731 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800732 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
733 return spv::BuiltInSubgroupSize;
734
Rex Xu574ab042016-04-14 16:53:07 +0800735 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800736 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800737 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
738 return spv::BuiltInSubgroupLocalInvocationId;
739
Rex Xu574ab042016-04-14 16:53:07 +0800740 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800741 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
742 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600743 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800744
Rex Xu574ab042016-04-14 16:53:07 +0800745 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800746 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
747 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600748 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800749
Rex Xu574ab042016-04-14 16:53:07 +0800750 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800751 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
752 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600753 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800754
Rex Xu574ab042016-04-14 16:53:07 +0800755 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800756 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
757 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600758 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800759
Rex Xu574ab042016-04-14 16:53:07 +0800760 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800761 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
762 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600763 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800764
John Kessenich66011cb2018-03-06 16:12:04 -0700765 case glslang::EbvNumSubgroups:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInNumSubgroups;
768
769 case glslang::EbvSubgroupID:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupId;
772
773 case glslang::EbvSubgroupSize2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 return spv::BuiltInSubgroupSize;
776
777 case glslang::EbvSubgroupInvocation2:
778 builder.addCapability(spv::CapabilityGroupNonUniform);
779 return spv::BuiltInSubgroupLocalInvocationId;
780
781 case glslang::EbvSubgroupEqMask2:
782 builder.addCapability(spv::CapabilityGroupNonUniform);
783 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
784 return spv::BuiltInSubgroupEqMask;
785
786 case glslang::EbvSubgroupGeMask2:
787 builder.addCapability(spv::CapabilityGroupNonUniform);
788 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
789 return spv::BuiltInSubgroupGeMask;
790
791 case glslang::EbvSubgroupGtMask2:
792 builder.addCapability(spv::CapabilityGroupNonUniform);
793 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
794 return spv::BuiltInSubgroupGtMask;
795
796 case glslang::EbvSubgroupLeMask2:
797 builder.addCapability(spv::CapabilityGroupNonUniform);
798 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
799 return spv::BuiltInSubgroupLeMask;
800
801 case glslang::EbvSubgroupLtMask2:
802 builder.addCapability(spv::CapabilityGroupNonUniform);
803 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
804 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600805
Rex Xu9d93a232016-05-05 12:30:44 +0800806#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800807 case glslang::EbvBaryCoordNoPersp:
808 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
809 return spv::BuiltInBaryCoordNoPerspAMD;
810
811 case glslang::EbvBaryCoordNoPerspCentroid:
812 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
813 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
814
815 case glslang::EbvBaryCoordNoPerspSample:
816 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
817 return spv::BuiltInBaryCoordNoPerspSampleAMD;
818
819 case glslang::EbvBaryCoordSmooth:
820 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
821 return spv::BuiltInBaryCoordSmoothAMD;
822
823 case glslang::EbvBaryCoordSmoothCentroid:
824 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
825 return spv::BuiltInBaryCoordSmoothCentroidAMD;
826
827 case glslang::EbvBaryCoordSmoothSample:
828 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
829 return spv::BuiltInBaryCoordSmoothSampleAMD;
830
831 case glslang::EbvBaryCoordPullModel:
832 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
833 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800834#endif
chaoc771d89f2017-01-13 01:10:53 -0800835
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700837 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700838 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700839 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700840
841 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700842 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700843 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700844 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700845
Daniel Koch5154db52018-11-26 10:01:58 -0500846 case glslang::EbvFragSizeEXT:
847 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
848 builder.addCapability(spv::CapabilityFragmentDensityEXT);
849 return spv::BuiltInFragSizeEXT;
850
851 case glslang::EbvFragInvocationCountEXT:
852 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
853 builder.addCapability(spv::CapabilityFragmentDensityEXT);
854 return spv::BuiltInFragInvocationCountEXT;
855
chaoc771d89f2017-01-13 01:10:53 -0800856#ifdef NV_EXTENSIONS
857 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800858 if (!memberDeclaration) {
859 builder.addExtension(spv::E_SPV_NV_viewport_array2);
860 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
861 }
chaoc771d89f2017-01-13 01:10:53 -0800862 return spv::BuiltInViewportMaskNV;
863 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800864 if (!memberDeclaration) {
865 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
866 builder.addCapability(spv::CapabilityShaderStereoViewNV);
867 }
chaoc771d89f2017-01-13 01:10:53 -0800868 return spv::BuiltInSecondaryPositionNV;
869 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800870 if (!memberDeclaration) {
871 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
872 builder.addCapability(spv::CapabilityShaderStereoViewNV);
873 }
chaoc771d89f2017-01-13 01:10:53 -0800874 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800875 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800876 if (!memberDeclaration) {
877 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
878 builder.addCapability(spv::CapabilityPerViewAttributesNV);
879 }
chaocdf3956c2017-02-14 14:52:34 -0800880 return spv::BuiltInPositionPerViewNV;
881 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800882 if (!memberDeclaration) {
883 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
884 builder.addCapability(spv::CapabilityPerViewAttributesNV);
885 }
chaocdf3956c2017-02-14 14:52:34 -0800886 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700887 case glslang::EbvFragFullyCoveredNV:
888 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
889 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
890 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700891 case glslang::EbvFragmentSizeNV:
892 builder.addExtension(spv::E_SPV_NV_shading_rate);
893 builder.addCapability(spv::CapabilityShadingRateNV);
894 return spv::BuiltInFragmentSizeNV;
895 case glslang::EbvInvocationsPerPixelNV:
896 builder.addExtension(spv::E_SPV_NV_shading_rate);
897 builder.addCapability(spv::CapabilityShadingRateNV);
898 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899
Daniel Koch593a4e02019-05-27 16:46:31 -0400900 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700917 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700918 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700919 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700920 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700921 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700922 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700923 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700924 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700925 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700926 return spv::BuiltInWorldToObjectNV;
927 case glslang::EbvIncomingRayFlagsNV:
928 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400929
930 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700931 case glslang::EbvBaryCoordNV:
932 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
933 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
934 return spv::BuiltInBaryCoordNV;
935 case glslang::EbvBaryCoordNoPerspNV:
936 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
937 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
938 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400939
940 // mesh shaders
941 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700942 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400943 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700944 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400945 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700946 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400947 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700948 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400949 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700950 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400951 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700952 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400953 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700954 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400955 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700956 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400957#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400958
959 // sm builtins
960 case glslang::EbvWarpsPerSM:
961 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
962 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
963 return spv::BuiltInWarpsPerSMNV;
964 case glslang::EbvSMCount:
965 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
966 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
967 return spv::BuiltInSMCountNV;
968 case glslang::EbvWarpID:
969 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
970 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
971 return spv::BuiltInWarpIDNV;
972 case glslang::EbvSMID:
973 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
974 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
975 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800976 default:
977 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600978 }
979}
980
Rex Xufc618912015-09-09 16:42:49 +0800981// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700982spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800983{
984 assert(type.getBasicType() == glslang::EbtSampler);
985
John Kessenich5d0fa972016-02-15 11:57:00 -0700986 // Check for capabilities
987 switch (type.getQualifier().layoutFormat) {
988 case glslang::ElfRg32f:
989 case glslang::ElfRg16f:
990 case glslang::ElfR11fG11fB10f:
991 case glslang::ElfR16f:
992 case glslang::ElfRgba16:
993 case glslang::ElfRgb10A2:
994 case glslang::ElfRg16:
995 case glslang::ElfRg8:
996 case glslang::ElfR16:
997 case glslang::ElfR8:
998 case glslang::ElfRgba16Snorm:
999 case glslang::ElfRg16Snorm:
1000 case glslang::ElfRg8Snorm:
1001 case glslang::ElfR16Snorm:
1002 case glslang::ElfR8Snorm:
1003
1004 case glslang::ElfRg32i:
1005 case glslang::ElfRg16i:
1006 case glslang::ElfRg8i:
1007 case glslang::ElfR16i:
1008 case glslang::ElfR8i:
1009
1010 case glslang::ElfRgb10a2ui:
1011 case glslang::ElfRg32ui:
1012 case glslang::ElfRg16ui:
1013 case glslang::ElfRg8ui:
1014 case glslang::ElfR16ui:
1015 case glslang::ElfR8ui:
1016 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1017 break;
1018
1019 default:
1020 break;
1021 }
1022
1023 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001024 switch (type.getQualifier().layoutFormat) {
1025 case glslang::ElfNone: return spv::ImageFormatUnknown;
1026 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1027 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1028 case glslang::ElfR32f: return spv::ImageFormatR32f;
1029 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1030 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1031 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1032 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1033 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1034 case glslang::ElfR16f: return spv::ImageFormatR16f;
1035 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1036 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1037 case glslang::ElfRg16: return spv::ImageFormatRg16;
1038 case glslang::ElfRg8: return spv::ImageFormatRg8;
1039 case glslang::ElfR16: return spv::ImageFormatR16;
1040 case glslang::ElfR8: return spv::ImageFormatR8;
1041 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1042 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1043 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1044 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1045 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1046 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1047 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1048 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1049 case glslang::ElfR32i: return spv::ImageFormatR32i;
1050 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1051 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1052 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1053 case glslang::ElfR16i: return spv::ImageFormatR16i;
1054 case glslang::ElfR8i: return spv::ImageFormatR8i;
1055 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1056 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1057 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1058 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1059 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1060 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1061 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1062 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1063 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1064 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001065 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001066 }
1067}
1068
John Kesseniche18fd202018-01-30 11:01:39 -07001069spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001070{
John Kesseniche18fd202018-01-30 11:01:39 -07001071 if (selectionNode.getFlatten())
1072 return spv::SelectionControlFlattenMask;
1073 if (selectionNode.getDontFlatten())
1074 return spv::SelectionControlDontFlattenMask;
1075 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001076}
1077
John Kesseniche18fd202018-01-30 11:01:39 -07001078spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001079{
John Kesseniche18fd202018-01-30 11:01:39 -07001080 if (switchNode.getFlatten())
1081 return spv::SelectionControlFlattenMask;
1082 if (switchNode.getDontFlatten())
1083 return spv::SelectionControlDontFlattenMask;
1084 return spv::SelectionControlMaskNone;
1085}
1086
John Kessenicha2858d92018-01-31 08:11:18 -07001087// return a non-0 dependency if the dependency argument must be set
1088spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001089 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001090{
1091 spv::LoopControlMask control = spv::LoopControlMaskNone;
1092
1093 if (loopNode.getDontUnroll())
1094 control = control | spv::LoopControlDontUnrollMask;
1095 if (loopNode.getUnroll())
1096 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001097 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001098 control = control | spv::LoopControlDependencyInfiniteMask;
1099 else if (loopNode.getLoopDependency() > 0) {
1100 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001101 operands.push_back((unsigned int)loopNode.getLoopDependency());
1102 }
1103 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1104 if (loopNode.getMinIterations() > 0) {
1105 control = control | spv::LoopControlMinIterationsMask;
1106 operands.push_back(loopNode.getMinIterations());
1107 }
1108 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1109 control = control | spv::LoopControlMaxIterationsMask;
1110 operands.push_back(loopNode.getMaxIterations());
1111 }
1112 if (loopNode.getIterationMultiple() > 1) {
1113 control = control | spv::LoopControlIterationMultipleMask;
1114 operands.push_back(loopNode.getIterationMultiple());
1115 }
1116 if (loopNode.getPeelCount() > 0) {
1117 control = control | spv::LoopControlPeelCountMask;
1118 operands.push_back(loopNode.getPeelCount());
1119 }
1120 if (loopNode.getPartialCount() > 0) {
1121 control = control | spv::LoopControlPartialCountMask;
1122 operands.push_back(loopNode.getPartialCount());
1123 }
John Kessenicha2858d92018-01-31 08:11:18 -07001124 }
John Kesseniche18fd202018-01-30 11:01:39 -07001125
1126 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001127}
1128
John Kessenicha5c5fb62017-05-05 05:09:58 -06001129// Translate glslang type to SPIR-V storage class.
1130spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1131{
1132 if (type.getQualifier().isPipeInput())
1133 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001134 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001135 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001136
1137 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1138 type.getQualifier().storage == glslang::EvqUniform) {
1139 if (type.getBasicType() == glslang::EbtAtomicUint)
1140 return spv::StorageClassAtomicCounter;
1141 if (type.containsOpaque())
1142 return spv::StorageClassUniformConstant;
1143 }
1144
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001145#ifdef NV_EXTENSIONS
1146 if (type.getQualifier().isUniformOrBuffer() &&
1147 type.getQualifier().layoutShaderRecordNV) {
1148 return spv::StorageClassShaderRecordBufferNV;
1149 }
1150#endif
1151
John Kessenichbed4e4f2017-09-08 02:38:07 -06001152 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001153 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001155 }
1156
1157 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001158 if (type.getQualifier().layoutPushConstant)
1159 return spv::StorageClassPushConstant;
1160 if (type.getBasicType() == glslang::EbtBlock)
1161 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001162 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001163 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001164
1165 switch (type.getQualifier().storage) {
1166 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1167 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1168 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1169 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001170#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001171 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1172 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1173 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1174 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1175 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001176#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001177 default:
1178 assert(0);
1179 break;
1180 }
1181
1182 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001183}
1184
John Kessenich5611c6d2018-04-05 11:25:02 -06001185// Add capabilities pertaining to how an array is indexed.
1186void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1187 const glslang::TType& indexType)
1188{
1189 if (indexType.getQualifier().isNonUniform()) {
1190 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001191 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001192 if (baseType.getBasicType() == glslang::EbtSampler) {
1193 if (baseType.getQualifier().hasAttachment())
1194 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1195 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1196 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1197 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1198 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1199 else if (baseType.isImage())
1200 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1201 else if (baseType.isTexture())
1202 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1203 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1204 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1205 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1206 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1207 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1208 }
1209 } else {
1210 // assume a dynamically uniform index
1211 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 if (baseType.getQualifier().hasAttachment()) {
1213 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001215 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1216 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001217 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001218 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1219 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001220 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001221 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001222 }
1223 }
1224}
1225
qining25262b32016-05-06 17:25:16 -04001226// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001227// descriptor set.
1228bool IsDescriptorResource(const glslang::TType& type)
1229{
John Kessenichf7497e22016-03-08 21:36:22 -07001230 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001231 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001232 return type.getQualifier().isUniformOrBuffer() &&
1233#ifdef NV_EXTENSIONS
1234 ! type.getQualifier().layoutShaderRecordNV &&
1235#endif
1236 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001237
1238 // non block...
1239 // basically samplerXXX/subpass/sampler/texture are all included
1240 // if they are the global-scope-class, not the function parameter
1241 // (or local, if they ever exist) class.
1242 if (type.getBasicType() == glslang::EbtSampler)
1243 return type.getQualifier().isUniformOrBuffer();
1244
1245 // None of the above.
1246 return false;
1247}
1248
John Kesseniche0b6cad2015-12-24 10:30:13 -07001249void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1250{
1251 if (child.layoutMatrix == glslang::ElmNone)
1252 child.layoutMatrix = parent.layoutMatrix;
1253
1254 if (parent.invariant)
1255 child.invariant = true;
1256 if (parent.nopersp)
1257 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001258#ifdef AMD_EXTENSIONS
1259 if (parent.explicitInterp)
1260 child.explicitInterp = true;
1261#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001262 if (parent.flat)
1263 child.flat = true;
1264 if (parent.centroid)
1265 child.centroid = true;
1266 if (parent.patch)
1267 child.patch = true;
1268 if (parent.sample)
1269 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001270 if (parent.coherent)
1271 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001272 if (parent.devicecoherent)
1273 child.devicecoherent = true;
1274 if (parent.queuefamilycoherent)
1275 child.queuefamilycoherent = true;
1276 if (parent.workgroupcoherent)
1277 child.workgroupcoherent = true;
1278 if (parent.subgroupcoherent)
1279 child.subgroupcoherent = true;
1280 if (parent.nonprivate)
1281 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001282 if (parent.volatil)
1283 child.volatil = true;
1284 if (parent.restrict)
1285 child.restrict = true;
1286 if (parent.readonly)
1287 child.readonly = true;
1288 if (parent.writeonly)
1289 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001290#ifdef NV_EXTENSIONS
1291 if (parent.perPrimitiveNV)
1292 child.perPrimitiveNV = true;
1293 if (parent.perViewNV)
1294 child.perViewNV = true;
1295 if (parent.perTaskNV)
1296 child.perTaskNV = true;
1297#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001298}
1299
John Kessenichf2b7f332016-09-01 17:05:23 -06001300bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001301{
John Kessenich7b9fa252016-01-21 18:56:57 -07001302 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001303 // - struct members might inherit from a struct declaration
1304 // (note that non-block structs don't explicitly inherit,
1305 // only implicitly, meaning no decoration involved)
1306 // - affect decorations on the struct members
1307 // (note smooth does not, and expecting something like volatile
1308 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001309 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001310 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001311}
1312
John Kessenich140f3df2015-06-26 16:58:36 -06001313//
1314// Implement the TGlslangToSpvTraverser class.
1315//
1316
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001317TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001318 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1319 : TIntermTraverser(true, false, true),
1320 options(options),
1321 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001322 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001323 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001324 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001325 glslangIntermediate(glslangIntermediate),
1326 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001327{
1328 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1329
1330 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001331 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1332 glslangIntermediate->getVersion());
1333
John Kessenich121853f2017-05-31 17:11:16 -06001334 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001335 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001336 builder.setSourceFile(glslangIntermediate->getSourceFile());
1337
1338 // Set the source shader's text. If for SPV version 1.0, include
1339 // a preamble in comments stating the OpModuleProcessed instructions.
1340 // Otherwise, emit those as actual instructions.
1341 std::string text;
1342 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1343 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001344 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001345 text.append("// OpModuleProcessed ");
1346 text.append(processes[p]);
1347 text.append("\n");
1348 } else
1349 builder.addModuleProcessed(processes[p]);
1350 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001351 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001352 text.append("#line 1\n");
1353 text.append(glslangIntermediate->getSourceText());
1354 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001355 // Pass name and text for all included files
1356 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1357 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1358 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001359 }
John Kessenich140f3df2015-06-26 16:58:36 -06001360 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001361
1362 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1363 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1364
1365 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1366 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1367 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1368 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1369 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001370 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001371 memoryModel = spv::MemoryModelVulkanKHR;
1372 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001373 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001374 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001375 builder.setMemoryModel(addressingModel, memoryModel);
1376
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001377 if (glslangIntermediate->usingVariablePointers()) {
1378 builder.addCapability(spv::CapabilityVariablePointers);
1379 }
1380
John Kessenicheee9d532016-09-19 18:09:30 -06001381 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1382 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001383
1384 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001385 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1386 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001387 builder.addSourceExtension(it->c_str());
1388
1389 // Add the top-level modes for this shader.
1390
John Kessenich92187592016-02-01 13:45:25 -07001391 if (glslangIntermediate->getXfbMode()) {
1392 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001394 }
John Kessenich140f3df2015-06-26 16:58:36 -06001395
1396 unsigned int mode;
1397 switch (glslangIntermediate->getStage()) {
1398 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001399 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001400 break;
1401
steve-lunarge7412492017-03-23 11:56:07 -06001402 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001403 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001404 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001405
steve-lunarge7412492017-03-23 11:56:07 -06001406 glslang::TLayoutGeometry primitive;
1407
1408 if (glslangIntermediate->getStage() == EShLangTessControl) {
1409 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1410 primitive = glslangIntermediate->getOutputPrimitive();
1411 } else {
1412 primitive = glslangIntermediate->getInputPrimitive();
1413 }
1414
1415 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001416 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1417 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1418 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001419 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 }
John Kessenich4016e382016-07-15 11:53:56 -06001421 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001422 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1423
John Kesseniche6903322015-10-13 16:29:02 -06001424 switch (glslangIntermediate->getVertexSpacing()) {
1425 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1426 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1427 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001428 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001429 }
John Kessenich4016e382016-07-15 11:53:56 -06001430 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001431 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1432
1433 switch (glslangIntermediate->getVertexOrder()) {
1434 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1435 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001436 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001437 }
John Kessenich4016e382016-07-15 11:53:56 -06001438 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001439 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1440
1441 if (glslangIntermediate->getPointMode())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001443 break;
1444
1445 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 switch (glslangIntermediate->getInputPrimitive()) {
1448 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1449 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1450 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001451 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001452 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001453 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001454 }
John Kessenich4016e382016-07-15 11:53:56 -06001455 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001456 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001457
John Kessenich140f3df2015-06-26 16:58:36 -06001458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1459
1460 switch (glslangIntermediate->getOutputPrimitive()) {
1461 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1462 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1463 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001464 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 }
John Kessenich4016e382016-07-15 11:53:56 -06001466 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1469 break;
1470
1471 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001472 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001473 if (glslangIntermediate->getPixelCenterInteger())
1474 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001475
John Kessenich140f3df2015-06-26 16:58:36 -06001476 if (glslangIntermediate->getOriginUpperLeft())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001478 else
1479 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001480
1481 if (glslangIntermediate->getEarlyFragmentTests())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1483
chaocc1204522017-06-30 17:14:30 -07001484 if (glslangIntermediate->getPostDepthCoverage()) {
1485 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1487 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1488 }
1489
John Kesseniche6903322015-10-13 16:29:02 -06001490 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001491 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1492 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001493 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001494 }
John Kessenich4016e382016-07-15 11:53:56 -06001495 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001496 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1497
1498 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1499 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001500
1501 switch (glslangIntermediate->getInterlockOrdering()) {
1502 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1503 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1504 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1505 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1506 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1507 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1508 default: mode = spv::ExecutionModeMax; break;
1509 }
1510 if (mode != spv::ExecutionModeMax) {
1511 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1512 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1513 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1514 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1515 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1516 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1517 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1518 } else {
1519 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1520 }
1521 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1522 }
1523
John Kessenich140f3df2015-06-26 16:58:36 -06001524 break;
1525
1526 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001527 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1529 glslangIntermediate->getLocalSize(1),
1530 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001531#ifdef NV_EXTENSIONS
1532 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1533 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1534 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1535 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1536 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1537 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1539 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1540 }
1541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001542 break;
1543
Chao Chen3c366992018-09-19 11:41:59 -07001544#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001545 case EShLangRayGenNV:
1546 case EShLangIntersectNV:
1547 case EShLangAnyHitNV:
1548 case EShLangClosestHitNV:
1549 case EShLangMissNV:
1550 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001551 builder.addCapability(spv::CapabilityRayTracingNV);
1552 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001553 break;
Chao Chen3c366992018-09-19 11:41:59 -07001554 case EShLangTaskNV:
1555 case EShLangMeshNV:
1556 builder.addCapability(spv::CapabilityMeshShadingNV);
1557 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1558 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1559 glslangIntermediate->getLocalSize(1),
1560 glslangIntermediate->getLocalSize(2));
1561 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1563 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1564
1565 switch (glslangIntermediate->getOutputPrimitive()) {
1566 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1567 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1568 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1569 default: mode = spv::ExecutionModeMax; break;
1570 }
1571 if (mode != spv::ExecutionModeMax)
1572 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1573 }
1574 break;
1575#endif
1576
John Kessenich140f3df2015-06-26 16:58:36 -06001577 default:
1578 break;
1579 }
John Kessenich140f3df2015-06-26 16:58:36 -06001580}
1581
John Kessenichfca82622016-11-26 13:23:20 -07001582// Finish creating SPV, after the traversal is complete.
1583void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001584{
John Kessenichf04c51b2018-08-03 15:56:12 -06001585 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001586 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001587 builder.setBuildPoint(shaderEntry->getLastBlock());
1588 builder.leaveFunction();
1589 }
1590
John Kessenich7ba63412015-12-20 17:37:07 -07001591 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001592 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1593 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001594
John Kessenichf04c51b2018-08-03 15:56:12 -06001595 // Add capabilities, extensions, remove unneeded decorations, etc.,
1596 // based on the resulting SPIR-V.
1597 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001598}
1599
John Kessenichfca82622016-11-26 13:23:20 -07001600// Write the SPV into 'out'.
1601void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001602{
John Kessenichfca82622016-11-26 13:23:20 -07001603 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001604}
1605
1606//
1607// Implement the traversal functions.
1608//
1609// Return true from interior nodes to have the external traversal
1610// continue on to children. Return false if children were
1611// already processed.
1612//
1613
1614//
qining25262b32016-05-06 17:25:16 -04001615// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001616// - uniform/input reads
1617// - output writes
1618// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1619// - something simple that degenerates into the last bullet
1620//
1621void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1622{
qining75d1d802016-04-06 14:42:01 -04001623 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1624 if (symbol->getType().getQualifier().isSpecConstant())
1625 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1626
John Kessenich140f3df2015-06-26 16:58:36 -06001627 // getSymbolId() will set up all the IO decorations on the first call.
1628 // Formal function parameters were mapped during makeFunctions().
1629 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001630
John Kessenich7ba63412015-12-20 17:37:07 -07001631 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001632 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001633 // Consider adding to the OpEntryPoint interface list.
1634 // Only looking at structures if they have at least one member.
1635 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1636 spv::StorageClass sc = builder.getStorageClass(id);
1637 // Before SPIR-V 1.4, we only want to include Input and Output.
1638 // Starting with SPIR-V 1.4, we want all globals.
1639 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1640 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001641 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001642 }
John Kessenich5f77d862017-09-19 11:09:59 -06001643 }
John Kessenich9c14f772019-06-17 08:38:35 -06001644
1645 // If the SPIR-V type is required to be different than the AST type,
1646 // translate now from the SPIR-V type to the AST type, for the consuming
1647 // operation.
1648 // Note this turns it from an l-value to an r-value.
1649 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1650 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1651 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001652 }
1653
1654 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001655 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001656 // Prepare to generate code for the access
1657
1658 // L-value chains will be computed left to right. We're on the symbol now,
1659 // which is the left-most part of the access chain, so now is "clear" time,
1660 // followed by setting the base.
1661 builder.clearAccessChain();
1662
1663 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001664 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001665 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001666 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001667 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001668 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001669 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001670 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001671 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1672 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001673 builder.setAccessChainRValue(id);
1674 else
1675 builder.setAccessChainLValue(id);
1676 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001677
1678 // Process linkage-only nodes for any special additional interface work.
1679 if (linkageOnly) {
1680 if (glslangIntermediate->getHlslFunctionality1()) {
1681 // Map implicit counter buffers to their originating buffers, which should have been
1682 // seen by now, given earlier pruning of unused counters, and preservation of order
1683 // of declaration.
1684 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1685 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1686 // Save possible originating buffers for counter buffers, keyed by
1687 // making the potential counter-buffer name.
1688 std::string keyName = symbol->getName().c_str();
1689 keyName = glslangIntermediate->addCounterBufferName(keyName);
1690 counterOriginator[keyName] = symbol;
1691 } else {
1692 // Handle a counter buffer, by finding the saved originating buffer.
1693 std::string keyName = symbol->getName().c_str();
1694 auto it = counterOriginator.find(keyName);
1695 if (it != counterOriginator.end()) {
1696 id = getSymbolId(it->second);
1697 if (id != spv::NoResult) {
1698 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001699 if (counterId != spv::NoResult) {
1700 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001701 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001702 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001703 }
1704 }
1705 }
1706 }
1707 }
1708 }
John Kessenich140f3df2015-06-26 16:58:36 -06001709}
1710
1711bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1712{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001713 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001714
qining40887662016-04-03 22:20:42 -04001715 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1716 if (node->getType().getQualifier().isSpecConstant())
1717 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1718
John Kessenich140f3df2015-06-26 16:58:36 -06001719 // First, handle special cases
1720 switch (node->getOp()) {
1721 case glslang::EOpAssign:
1722 case glslang::EOpAddAssign:
1723 case glslang::EOpSubAssign:
1724 case glslang::EOpMulAssign:
1725 case glslang::EOpVectorTimesMatrixAssign:
1726 case glslang::EOpVectorTimesScalarAssign:
1727 case glslang::EOpMatrixTimesScalarAssign:
1728 case glslang::EOpMatrixTimesMatrixAssign:
1729 case glslang::EOpDivAssign:
1730 case glslang::EOpModAssign:
1731 case glslang::EOpAndAssign:
1732 case glslang::EOpInclusiveOrAssign:
1733 case glslang::EOpExclusiveOrAssign:
1734 case glslang::EOpLeftShiftAssign:
1735 case glslang::EOpRightShiftAssign:
1736 // A bin-op assign "a += b" means the same thing as "a = a + b"
1737 // where a is evaluated before b. For a simple assignment, GLSL
1738 // says to evaluate the left before the right. So, always, left
1739 // node then right node.
1740 {
1741 // get the left l-value, save it away
1742 builder.clearAccessChain();
1743 node->getLeft()->traverse(this);
1744 spv::Builder::AccessChain lValue = builder.getAccessChain();
1745
1746 // evaluate the right
1747 builder.clearAccessChain();
1748 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001749 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001750
1751 if (node->getOp() != glslang::EOpAssign) {
1752 // the left is also an r-value
1753 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001754 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001755
1756 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001757 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001758 TranslateNoContractionDecoration(node->getType().getQualifier()),
1759 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001760 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001761 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1762 node->getType().getBasicType());
1763
1764 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001765 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001766 }
1767
1768 // store the result
1769 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001770 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001771
1772 // assignments are expressions having an rValue after they are evaluated...
1773 builder.clearAccessChain();
1774 builder.setAccessChainRValue(rValue);
1775 }
1776 return false;
1777 case glslang::EOpIndexDirect:
1778 case glslang::EOpIndexDirectStruct:
1779 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001780 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001781 // Get the left part of the access chain.
1782 node->getLeft()->traverse(this);
1783
1784 // Add the next element in the chain
1785
David Netoa901ffe2016-06-08 14:11:40 +01001786 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001787 if (! node->getLeft()->getType().isArray() &&
1788 node->getLeft()->getType().isVector() &&
1789 node->getOp() == glslang::EOpIndexDirect) {
1790 // This is essentially a hard-coded vector swizzle of size 1,
1791 // so short circuit the access-chain stuff with a swizzle.
1792 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001793 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001794 int dummySize;
1795 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1796 TranslateCoherent(node->getLeft()->getType()),
1797 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001798 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001799
1800 // Load through a block reference is performed with a dot operator that
1801 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1802 // do a load and reset the access chain.
1803 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1804 !node->getLeft()->getType().isArray() &&
1805 node->getOp() == glslang::EOpIndexDirectStruct)
1806 {
1807 spv::Id left = accessChainLoad(node->getLeft()->getType());
1808 builder.clearAccessChain();
1809 builder.setAccessChainLValue(left);
1810 }
1811
David Netoa901ffe2016-06-08 14:11:40 +01001812 int spvIndex = glslangIndex;
1813 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1814 node->getOp() == glslang::EOpIndexDirectStruct)
1815 {
1816 // This may be, e.g., an anonymous block-member selection, which generally need
1817 // index remapping due to hidden members in anonymous blocks.
1818 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1819 assert(remapper.size() > 0);
1820 spvIndex = remapper[glslangIndex];
1821 }
John Kessenichebb50532016-05-16 19:22:05 -06001822
David Netoa901ffe2016-06-08 14:11:40 +01001823 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001824 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001825
1826 // Add capabilities here for accessing PointSize and clip/cull distance.
1827 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001828 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001829 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001830 }
1831 }
1832 return false;
1833 case glslang::EOpIndexIndirect:
1834 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001835 // Array, matrix, or vector indirection with variable index.
1836 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001837 // matrices are arrays of vectors, so will also work for a matrix.
1838 // Will use the access chain's 'component' for variable index into a vector.
1839
1840 // This adapter is building access chains left to right.
1841 // Set up the access chain to the left.
1842 node->getLeft()->traverse(this);
1843
1844 // save it so that computing the right side doesn't trash it
1845 spv::Builder::AccessChain partial = builder.getAccessChain();
1846
1847 // compute the next index in the chain
1848 builder.clearAccessChain();
1849 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001850 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001851
John Kessenich5611c6d2018-04-05 11:25:02 -06001852 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1853
John Kessenich140f3df2015-06-26 16:58:36 -06001854 // restore the saved access chain
1855 builder.setAccessChain(partial);
1856
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001857 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1858 int dummySize;
1859 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1860 TranslateCoherent(node->getLeft()->getType()),
1861 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1862 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001863 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865 return false;
1866 case glslang::EOpVectorSwizzle:
1867 {
1868 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001870 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001871 int dummySize;
1872 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1873 TranslateCoherent(node->getLeft()->getType()),
1874 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001877 case glslang::EOpMatrixSwizzle:
1878 logger->missingFunctionality("matrix swizzle");
1879 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001880 case glslang::EOpLogicalOr:
1881 case glslang::EOpLogicalAnd:
1882 {
1883
1884 // These may require short circuiting, but can sometimes be done as straight
1885 // binary operations. The right operand must be short circuited if it has
1886 // side effects, and should probably be if it is complex.
1887 if (isTrivial(node->getRight()->getAsTyped()))
1888 break; // handle below as a normal binary operation
1889 // otherwise, we need to do dynamic short circuiting on the right operand
1890 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1891 builder.clearAccessChain();
1892 builder.setAccessChainRValue(result);
1893 }
1894 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001895 default:
1896 break;
1897 }
1898
1899 // Assume generic binary op...
1900
John Kessenich32cfd492016-02-02 12:37:46 -07001901 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001902 builder.clearAccessChain();
1903 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001904 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001905
John Kessenich32cfd492016-02-02 12:37:46 -07001906 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001907 builder.clearAccessChain();
1908 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001909 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001910
John Kessenich32cfd492016-02-02 12:37:46 -07001911 // get result
John Kessenichead86222018-03-28 18:01:20 -06001912 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001913 TranslateNoContractionDecoration(node->getType().getQualifier()),
1914 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001915 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001916 convertGlslangToSpvType(node->getType()), left, right,
1917 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001918
John Kessenich50e57562015-12-21 21:21:11 -07001919 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001920 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001921 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001922 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001923 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001924 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 return false;
1926 }
John Kessenich140f3df2015-06-26 16:58:36 -06001927}
1928
John Kessenich9c14f772019-06-17 08:38:35 -06001929// Figure out what, if any, type changes are needed when accessing a specific built-in.
1930// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1931// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1932std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1933 const glslang::TType& glslangType)
1934{
1935 switch(builtIn)
1936 {
1937 case spv::BuiltInSubgroupEqMask:
1938 case spv::BuiltInSubgroupGeMask:
1939 case spv::BuiltInSubgroupGtMask:
1940 case spv::BuiltInSubgroupLeMask:
1941 case spv::BuiltInSubgroupLtMask: {
1942 // these require changing a 64-bit scaler -> a vector of 32-bit components
1943 if (glslangType.isVector())
1944 break;
1945 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1946 builder.makeUintType(64));
1947 return ret;
1948 }
1949 default:
1950 break;
1951 }
1952
1953 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1954 return ret;
1955}
1956
1957// For an object previously identified (see getForcedType() and forceType)
1958// as needing type translations, do the translation needed for a load, turning
1959// an L-value into in R-value.
1960spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1961{
1962 const auto forceIt = forceType.find(object);
1963 if (forceIt == forceType.end())
1964 return object;
1965
1966 spv::Id desiredTypeId = forceIt->second;
1967 spv::Id objectTypeId = builder.getTypeId(object);
1968 assert(builder.isPointerType(objectTypeId));
1969 objectTypeId = builder.getContainedTypeId(objectTypeId);
1970 if (builder.isVectorType(objectTypeId) &&
1971 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1972 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1973 // handle 32-bit v.xy* -> 64-bit
1974 builder.clearAccessChain();
1975 builder.setAccessChainLValue(object);
1976 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1977 std::vector<spv::Id> components;
1978 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1979 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1980
1981 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1982 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1983 builder.createCompositeConstruct(vecType, components));
1984 } else {
1985 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1986 }
1987 } else {
1988 logger->missingFunctionality("forcing non 32-bit vector type");
1989 }
1990
1991 return object;
1992}
1993
John Kessenich140f3df2015-06-26 16:58:36 -06001994bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1995{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001996 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001997
qining40887662016-04-03 22:20:42 -04001998 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1999 if (node->getType().getQualifier().isSpecConstant())
2000 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2001
John Kessenichfc51d282015-08-19 13:34:18 -06002002 spv::Id result = spv::NoResult;
2003
2004 // try texturing first
2005 result = createImageTextureFunctionCall(node);
2006 if (result != spv::NoResult) {
2007 builder.clearAccessChain();
2008 builder.setAccessChainRValue(result);
2009
2010 return false; // done with this node
2011 }
2012
2013 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002014
2015 if (node->getOp() == glslang::EOpArrayLength) {
2016 // Quite special; won't want to evaluate the operand.
2017
John Kessenich5611c6d2018-04-05 11:25:02 -06002018 // Currently, the front-end does not allow .length() on an array until it is sized,
2019 // except for the last block membeor of an SSBO.
2020 // TODO: If this changes, link-time sized arrays might show up here, and need their
2021 // size extracted.
2022
John Kessenichc9a80832015-09-12 12:17:44 -06002023 // Normal .length() would have been constant folded by the front-end.
2024 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002025 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002026
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002027 spv::Id length;
2028 if (node->getOperand()->getType().isCoopMat()) {
2029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2030
2031 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2032 assert(builder.isCooperativeMatrixType(typeId));
2033
2034 length = builder.createCooperativeMatrixLength(typeId);
2035 } else {
2036 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2037 block->traverse(this);
2038 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2039 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2040 }
John Kessenichc9a80832015-09-12 12:17:44 -06002041
John Kessenich8c869672018-11-28 07:01:37 -07002042 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2043 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2044 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002045 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2046 if (builder.isInSpecConstCodeGenMode()) {
2047 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2048 } else {
2049 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2050 }
2051 }
John Kessenich8c869672018-11-28 07:01:37 -07002052
John Kessenichc9a80832015-09-12 12:17:44 -06002053 builder.clearAccessChain();
2054 builder.setAccessChainRValue(length);
2055
2056 return false;
2057 }
2058
John Kessenichfc51d282015-08-19 13:34:18 -06002059 // Start by evaluating the operand
2060
John Kessenich8c8505c2016-07-26 12:50:38 -06002061 // Does it need a swizzle inversion? If so, evaluation is inverted;
2062 // operate first on the swizzle base, then apply the swizzle.
2063 spv::Id invertedType = spv::NoType;
2064 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2065 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2066 invertedType = getInvertedSwizzleType(*node->getOperand());
2067
John Kessenich140f3df2015-06-26 16:58:36 -06002068 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002069 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002070 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002071 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002072 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002073 operandNode = node->getOperand();
2074
2075 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002076
Rex Xufc618912015-09-09 16:42:49 +08002077 spv::Id operand = spv::NoResult;
2078
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002079 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2080
Rex Xufc618912015-09-09 16:42:49 +08002081 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2082 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002083 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002084 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002085 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002086 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2087 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2088 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002089 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002090
John Kessenichead86222018-03-28 18:01:20 -06002091 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002092 TranslateNoContractionDecoration(node->getType().getQualifier()),
2093 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002094
2095 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002096 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002097 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098
2099 // if not, then possibly an operation
2100 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002101 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002102
2103 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002104 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002105 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002106 builder.addDecoration(result, decorations.nonUniform);
2107 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002108
John Kessenich140f3df2015-06-26 16:58:36 -06002109 builder.clearAccessChain();
2110 builder.setAccessChainRValue(result);
2111
2112 return false; // done with this node
2113 }
2114
2115 // it must be a special case, check...
2116 switch (node->getOp()) {
2117 case glslang::EOpPostIncrement:
2118 case glslang::EOpPostDecrement:
2119 case glslang::EOpPreIncrement:
2120 case glslang::EOpPreDecrement:
2121 {
2122 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002123 spv::Id one = 0;
2124 if (node->getBasicType() == glslang::EbtFloat)
2125 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002126 else if (node->getBasicType() == glslang::EbtDouble)
2127 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002128 else if (node->getBasicType() == glslang::EbtFloat16)
2129 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002130 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2131 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002132 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2133 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002134 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2135 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002136 else
2137 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002138 glslang::TOperator op;
2139 if (node->getOp() == glslang::EOpPreIncrement ||
2140 node->getOp() == glslang::EOpPostIncrement)
2141 op = glslang::EOpAdd;
2142 else
2143 op = glslang::EOpSub;
2144
John Kessenichead86222018-03-28 18:01:20 -06002145 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002146 convertGlslangToSpvType(node->getType()), operand, one,
2147 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002148 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002149
2150 // The result of operation is always stored, but conditionally the
2151 // consumed result. The consumed result is always an r-value.
2152 builder.accessChainStore(result);
2153 builder.clearAccessChain();
2154 if (node->getOp() == glslang::EOpPreIncrement ||
2155 node->getOp() == glslang::EOpPreDecrement)
2156 builder.setAccessChainRValue(result);
2157 else
2158 builder.setAccessChainRValue(operand);
2159 }
2160
2161 return false;
2162
2163 case glslang::EOpEmitStreamVertex:
2164 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2165 return false;
2166 case glslang::EOpEndStreamPrimitive:
2167 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2168 return false;
2169
2170 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002171 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002172 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002173 }
John Kessenich140f3df2015-06-26 16:58:36 -06002174}
2175
Jeff Bolz53134492019-06-25 13:31:10 -05002176// Construct a composite object, recursively copying members if their types don't match
2177spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2178{
2179 for (int c = 0; c < (int)constituents.size(); ++c) {
2180 spv::Id& constituent = constituents[c];
2181 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2182 spv::Id rType = builder.getTypeId(constituent);
2183 if (lType != rType) {
2184 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2185 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2186 } else if (builder.isStructType(rType)) {
2187 std::vector<spv::Id> rTypeConstituents;
2188 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2189 for (int i = 0; i < numrTypeConstituents; ++i) {
2190 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2191 }
2192 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2193 } else {
2194 assert(builder.isArrayType(rType));
2195 std::vector<spv::Id> rTypeConstituents;
2196 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2197
2198 spv::Id elementRType = builder.getContainedTypeId(rType);
2199 for (int i = 0; i < numrTypeConstituents; ++i) {
2200 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2201 }
2202 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2203 }
2204 }
2205 }
2206 return builder.createCompositeConstruct(resultTypeId, constituents);
2207}
2208
John Kessenich140f3df2015-06-26 16:58:36 -06002209bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2210{
qining27e04a02016-04-14 16:40:20 -04002211 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2212 if (node->getType().getQualifier().isSpecConstant())
2213 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2214
John Kessenichfc51d282015-08-19 13:34:18 -06002215 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002216 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2217 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002218
2219 // try texturing
2220 result = createImageTextureFunctionCall(node);
2221 if (result != spv::NoResult) {
2222 builder.clearAccessChain();
2223 builder.setAccessChainRValue(result);
2224
2225 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002226 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002227#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002228 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002229#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002230 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002231 // "imageStore" is a special case, which has no result
2232 return false;
2233 }
John Kessenichfc51d282015-08-19 13:34:18 -06002234
John Kessenich140f3df2015-06-26 16:58:36 -06002235 glslang::TOperator binOp = glslang::EOpNull;
2236 bool reduceComparison = true;
2237 bool isMatrix = false;
2238 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002239 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002240
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002241 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2242
John Kessenich140f3df2015-06-26 16:58:36 -06002243 assert(node->getOp());
2244
John Kessenichf6640762016-08-01 19:44:00 -06002245 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002246
2247 switch (node->getOp()) {
2248 case glslang::EOpSequence:
2249 {
2250 if (preVisit)
2251 ++sequenceDepth;
2252 else
2253 --sequenceDepth;
2254
2255 if (sequenceDepth == 1) {
2256 // If this is the parent node of all the functions, we want to see them
2257 // early, so all call points have actual SPIR-V functions to reference.
2258 // In all cases, still let the traverser visit the children for us.
2259 makeFunctions(node->getAsAggregate()->getSequence());
2260
John Kessenich6fccb3c2016-09-19 16:01:41 -06002261 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002262 // anything else gets there, so visit out of order, doing them all now.
2263 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2264
John Kessenich6a60c2f2016-12-08 21:01:59 -07002265 // 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 -06002266 // so do them manually.
2267 visitFunctions(node->getAsAggregate()->getSequence());
2268
2269 return false;
2270 }
2271
2272 return true;
2273 }
2274 case glslang::EOpLinkerObjects:
2275 {
2276 if (visit == glslang::EvPreVisit)
2277 linkageOnly = true;
2278 else
2279 linkageOnly = false;
2280
2281 return true;
2282 }
2283 case glslang::EOpComma:
2284 {
2285 // processing from left to right naturally leaves the right-most
2286 // lying around in the access chain
2287 glslang::TIntermSequence& glslangOperands = node->getSequence();
2288 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2289 glslangOperands[i]->traverse(this);
2290
2291 return false;
2292 }
2293 case glslang::EOpFunction:
2294 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002295 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002296 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002298 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 } else {
2300 handleFunctionEntry(node);
2301 }
2302 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002303 if (inEntryPoint)
2304 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002305 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002306 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002307 }
2308
2309 return true;
2310 case glslang::EOpParameters:
2311 // Parameters will have been consumed by EOpFunction processing, but not
2312 // the body, so we still visited the function node's children, making this
2313 // child redundant.
2314 return false;
2315 case glslang::EOpFunctionCall:
2316 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002317 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002318 if (node->isUserDefined())
2319 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002320 // 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 -07002321 if (result) {
2322 builder.clearAccessChain();
2323 builder.setAccessChainRValue(result);
2324 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002325 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002326
2327 return false;
2328 }
2329 case glslang::EOpConstructMat2x2:
2330 case glslang::EOpConstructMat2x3:
2331 case glslang::EOpConstructMat2x4:
2332 case glslang::EOpConstructMat3x2:
2333 case glslang::EOpConstructMat3x3:
2334 case glslang::EOpConstructMat3x4:
2335 case glslang::EOpConstructMat4x2:
2336 case glslang::EOpConstructMat4x3:
2337 case glslang::EOpConstructMat4x4:
2338 case glslang::EOpConstructDMat2x2:
2339 case glslang::EOpConstructDMat2x3:
2340 case glslang::EOpConstructDMat2x4:
2341 case glslang::EOpConstructDMat3x2:
2342 case glslang::EOpConstructDMat3x3:
2343 case glslang::EOpConstructDMat3x4:
2344 case glslang::EOpConstructDMat4x2:
2345 case glslang::EOpConstructDMat4x3:
2346 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002347 case glslang::EOpConstructIMat2x2:
2348 case glslang::EOpConstructIMat2x3:
2349 case glslang::EOpConstructIMat2x4:
2350 case glslang::EOpConstructIMat3x2:
2351 case glslang::EOpConstructIMat3x3:
2352 case glslang::EOpConstructIMat3x4:
2353 case glslang::EOpConstructIMat4x2:
2354 case glslang::EOpConstructIMat4x3:
2355 case glslang::EOpConstructIMat4x4:
2356 case glslang::EOpConstructUMat2x2:
2357 case glslang::EOpConstructUMat2x3:
2358 case glslang::EOpConstructUMat2x4:
2359 case glslang::EOpConstructUMat3x2:
2360 case glslang::EOpConstructUMat3x3:
2361 case glslang::EOpConstructUMat3x4:
2362 case glslang::EOpConstructUMat4x2:
2363 case glslang::EOpConstructUMat4x3:
2364 case glslang::EOpConstructUMat4x4:
2365 case glslang::EOpConstructBMat2x2:
2366 case glslang::EOpConstructBMat2x3:
2367 case glslang::EOpConstructBMat2x4:
2368 case glslang::EOpConstructBMat3x2:
2369 case glslang::EOpConstructBMat3x3:
2370 case glslang::EOpConstructBMat3x4:
2371 case glslang::EOpConstructBMat4x2:
2372 case glslang::EOpConstructBMat4x3:
2373 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002374 case glslang::EOpConstructF16Mat2x2:
2375 case glslang::EOpConstructF16Mat2x3:
2376 case glslang::EOpConstructF16Mat2x4:
2377 case glslang::EOpConstructF16Mat3x2:
2378 case glslang::EOpConstructF16Mat3x3:
2379 case glslang::EOpConstructF16Mat3x4:
2380 case glslang::EOpConstructF16Mat4x2:
2381 case glslang::EOpConstructF16Mat4x3:
2382 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002383 isMatrix = true;
2384 // fall through
2385 case glslang::EOpConstructFloat:
2386 case glslang::EOpConstructVec2:
2387 case glslang::EOpConstructVec3:
2388 case glslang::EOpConstructVec4:
2389 case glslang::EOpConstructDouble:
2390 case glslang::EOpConstructDVec2:
2391 case glslang::EOpConstructDVec3:
2392 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002393 case glslang::EOpConstructFloat16:
2394 case glslang::EOpConstructF16Vec2:
2395 case glslang::EOpConstructF16Vec3:
2396 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002397 case glslang::EOpConstructBool:
2398 case glslang::EOpConstructBVec2:
2399 case glslang::EOpConstructBVec3:
2400 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002401 case glslang::EOpConstructInt8:
2402 case glslang::EOpConstructI8Vec2:
2403 case glslang::EOpConstructI8Vec3:
2404 case glslang::EOpConstructI8Vec4:
2405 case glslang::EOpConstructUint8:
2406 case glslang::EOpConstructU8Vec2:
2407 case glslang::EOpConstructU8Vec3:
2408 case glslang::EOpConstructU8Vec4:
2409 case glslang::EOpConstructInt16:
2410 case glslang::EOpConstructI16Vec2:
2411 case glslang::EOpConstructI16Vec3:
2412 case glslang::EOpConstructI16Vec4:
2413 case glslang::EOpConstructUint16:
2414 case glslang::EOpConstructU16Vec2:
2415 case glslang::EOpConstructU16Vec3:
2416 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002417 case glslang::EOpConstructInt:
2418 case glslang::EOpConstructIVec2:
2419 case glslang::EOpConstructIVec3:
2420 case glslang::EOpConstructIVec4:
2421 case glslang::EOpConstructUint:
2422 case glslang::EOpConstructUVec2:
2423 case glslang::EOpConstructUVec3:
2424 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002425 case glslang::EOpConstructInt64:
2426 case glslang::EOpConstructI64Vec2:
2427 case glslang::EOpConstructI64Vec3:
2428 case glslang::EOpConstructI64Vec4:
2429 case glslang::EOpConstructUint64:
2430 case glslang::EOpConstructU64Vec2:
2431 case glslang::EOpConstructU64Vec3:
2432 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002433 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002434 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002435 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002436 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002437 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002438 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002439 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002440 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002441 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002442 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002443 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002444 else if (node->getOp() == glslang::EOpConstructStruct ||
2445 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2446 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002447 std::vector<spv::Id> constituents;
2448 for (int c = 0; c < (int)arguments.size(); ++c)
2449 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002450 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002451 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002452 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002453 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002454 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002455
2456 builder.clearAccessChain();
2457 builder.setAccessChainRValue(constructed);
2458
2459 return false;
2460 }
2461
2462 // These six are component-wise compares with component-wise results.
2463 // Forward on to createBinaryOperation(), requesting a vector result.
2464 case glslang::EOpLessThan:
2465 case glslang::EOpGreaterThan:
2466 case glslang::EOpLessThanEqual:
2467 case glslang::EOpGreaterThanEqual:
2468 case glslang::EOpVectorEqual:
2469 case glslang::EOpVectorNotEqual:
2470 {
2471 // Map the operation to a binary
2472 binOp = node->getOp();
2473 reduceComparison = false;
2474 switch (node->getOp()) {
2475 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2476 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2477 default: binOp = node->getOp(); break;
2478 }
2479
2480 break;
2481 }
2482 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002483 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002484 binOp = glslang::EOpMul;
2485 break;
2486 case glslang::EOpOuterProduct:
2487 // two vectors multiplied to make a matrix
2488 binOp = glslang::EOpOuterProduct;
2489 break;
2490 case glslang::EOpDot:
2491 {
qining25262b32016-05-06 17:25:16 -04002492 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002493 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002494 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002495 binOp = glslang::EOpMul;
2496 break;
2497 }
2498 case glslang::EOpMod:
2499 // when an aggregate, this is the floating-point mod built-in function,
2500 // which can be emitted by the one in createBinaryOperation()
2501 binOp = glslang::EOpMod;
2502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002503 case glslang::EOpEmitVertex:
2504 case glslang::EOpEndPrimitive:
2505 case glslang::EOpBarrier:
2506 case glslang::EOpMemoryBarrier:
2507 case glslang::EOpMemoryBarrierAtomicCounter:
2508 case glslang::EOpMemoryBarrierBuffer:
2509 case glslang::EOpMemoryBarrierImage:
2510 case glslang::EOpMemoryBarrierShared:
2511 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002512 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002513 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002514 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002515 case glslang::EOpWorkgroupMemoryBarrier:
2516 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002517 case glslang::EOpSubgroupBarrier:
2518 case glslang::EOpSubgroupMemoryBarrier:
2519 case glslang::EOpSubgroupMemoryBarrierBuffer:
2520 case glslang::EOpSubgroupMemoryBarrierImage:
2521 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002522 noReturnValue = true;
2523 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2524 break;
2525
Jeff Bolz36831c92018-09-05 10:11:41 -05002526 case glslang::EOpAtomicStore:
2527 noReturnValue = true;
2528 // fallthrough
2529 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002530 case glslang::EOpAtomicAdd:
2531 case glslang::EOpAtomicMin:
2532 case glslang::EOpAtomicMax:
2533 case glslang::EOpAtomicAnd:
2534 case glslang::EOpAtomicOr:
2535 case glslang::EOpAtomicXor:
2536 case glslang::EOpAtomicExchange:
2537 case glslang::EOpAtomicCompSwap:
2538 atomic = true;
2539 break;
2540
John Kessenich0d0c6d32017-07-23 16:08:26 -06002541 case glslang::EOpAtomicCounterAdd:
2542 case glslang::EOpAtomicCounterSubtract:
2543 case glslang::EOpAtomicCounterMin:
2544 case glslang::EOpAtomicCounterMax:
2545 case glslang::EOpAtomicCounterAnd:
2546 case glslang::EOpAtomicCounterOr:
2547 case glslang::EOpAtomicCounterXor:
2548 case glslang::EOpAtomicCounterExchange:
2549 case glslang::EOpAtomicCounterCompSwap:
2550 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2551 builder.addCapability(spv::CapabilityAtomicStorageOps);
2552 atomic = true;
2553 break;
2554
Chao Chen3c366992018-09-19 11:41:59 -07002555#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002556 case glslang::EOpIgnoreIntersectionNV:
2557 case glslang::EOpTerminateRayNV:
2558 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002559 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002560 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2561 noReturnValue = true;
2562 break;
2563#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002564 case glslang::EOpCooperativeMatrixLoad:
2565 case glslang::EOpCooperativeMatrixStore:
2566 noReturnValue = true;
2567 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002568 case glslang::EOpBeginInvocationInterlock:
2569 case glslang::EOpEndInvocationInterlock:
2570 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2571 noReturnValue = true;
2572 break;
Chao Chen3c366992018-09-19 11:41:59 -07002573
John Kessenich140f3df2015-06-26 16:58:36 -06002574 default:
2575 break;
2576 }
2577
2578 //
2579 // See if it maps to a regular operation.
2580 //
John Kessenich140f3df2015-06-26 16:58:36 -06002581 if (binOp != glslang::EOpNull) {
2582 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2583 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2584 assert(left && right);
2585
2586 builder.clearAccessChain();
2587 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002588 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002589
2590 builder.clearAccessChain();
2591 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002592 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002593
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002594 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002595 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002596 TranslateNoContractionDecoration(node->getType().getQualifier()),
2597 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002598 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002599 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002600 left->getType().getBasicType(), reduceComparison);
2601
2602 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002603 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002604 builder.clearAccessChain();
2605 builder.setAccessChainRValue(result);
2606
2607 return false;
2608 }
2609
John Kessenich426394d2015-07-23 10:22:48 -06002610 //
2611 // Create the list of operands.
2612 //
John Kessenich140f3df2015-06-26 16:58:36 -06002613 glslang::TIntermSequence& glslangOperands = node->getSequence();
2614 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002615 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002617 // special case l-value operands; there are just a few
2618 bool lvalue = false;
2619 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002620 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002621 case glslang::EOpModf:
2622 if (arg == 1)
2623 lvalue = true;
2624 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002625 case glslang::EOpInterpolateAtSample:
2626 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002627#ifdef AMD_EXTENSIONS
2628 case glslang::EOpInterpolateAtVertex:
2629#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002630 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002631 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002632
2633 // Does it need a swizzle inversion? If so, evaluation is inverted;
2634 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002635 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002636 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2637 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2638 }
Rex Xu7a26c172015-12-08 17:12:09 +08002639 break;
Rex Xud4782c12015-09-06 16:30:11 +08002640 case glslang::EOpAtomicAdd:
2641 case glslang::EOpAtomicMin:
2642 case glslang::EOpAtomicMax:
2643 case glslang::EOpAtomicAnd:
2644 case glslang::EOpAtomicOr:
2645 case glslang::EOpAtomicXor:
2646 case glslang::EOpAtomicExchange:
2647 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002648 case glslang::EOpAtomicLoad:
2649 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002650 case glslang::EOpAtomicCounterAdd:
2651 case glslang::EOpAtomicCounterSubtract:
2652 case glslang::EOpAtomicCounterMin:
2653 case glslang::EOpAtomicCounterMax:
2654 case glslang::EOpAtomicCounterAnd:
2655 case glslang::EOpAtomicCounterOr:
2656 case glslang::EOpAtomicCounterXor:
2657 case glslang::EOpAtomicCounterExchange:
2658 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002659 if (arg == 0)
2660 lvalue = true;
2661 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002662 case glslang::EOpAddCarry:
2663 case glslang::EOpSubBorrow:
2664 if (arg == 2)
2665 lvalue = true;
2666 break;
2667 case glslang::EOpUMulExtended:
2668 case glslang::EOpIMulExtended:
2669 if (arg >= 2)
2670 lvalue = true;
2671 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002672 case glslang::EOpCooperativeMatrixLoad:
2673 if (arg == 0 || arg == 1)
2674 lvalue = true;
2675 break;
2676 case glslang::EOpCooperativeMatrixStore:
2677 if (arg == 1)
2678 lvalue = true;
2679 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002680 default:
2681 break;
2682 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002683 builder.clearAccessChain();
2684 if (invertedType != spv::NoType && arg == 0)
2685 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2686 else
2687 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002688
2689 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2690 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2691
2692 if (arg == 1) {
2693 // fold "element" parameter into the access chain
2694 spv::Builder::AccessChain save = builder.getAccessChain();
2695 builder.clearAccessChain();
2696 glslangOperands[2]->traverse(this);
2697
2698 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2699
2700 builder.setAccessChain(save);
2701
2702 // Point to the first element of the array.
2703 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002704 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002705
2706 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2707 unsigned int alignment = builder.getAccessChain().alignment;
2708
2709 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2710 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2711 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2712 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2713 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2714 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2715 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2716 }
2717
2718 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2719
2720 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2721 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2722 }
2723
2724 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2725 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2726 }
2727 } else if (arg == 2) {
2728 continue;
2729 }
2730 }
2731
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002732 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002733 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002734 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2735 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2736 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002737 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002738 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002739 }
John Kessenich140f3df2015-06-26 16:58:36 -06002740 }
John Kessenich426394d2015-07-23 10:22:48 -06002741
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002742 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002743 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2744 std::vector<spv::IdImmediate> idImmOps;
2745
2746 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2747 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2748 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2749 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2750 // get the pointee type
2751 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2752 assert(builder.isCooperativeMatrixType(typeId));
2753 // do the op
2754 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2755 // store the result to the pointer (out param 'm')
2756 builder.createStore(result, operands[0]);
2757 result = 0;
2758 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2759 std::vector<spv::IdImmediate> idImmOps;
2760
2761 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2762 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2763 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2764 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2765 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2766
2767 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2768 result = 0;
2769 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002770 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002771 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002772 } else {
2773 // Pass through to generic operations.
2774 switch (glslangOperands.size()) {
2775 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002776 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002777 break;
2778 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002779 {
2780 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002781 TranslateNoContractionDecoration(node->getType().getQualifier()),
2782 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002783 result = createUnaryOperation(
2784 node->getOp(), decorations,
2785 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002786 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002787 }
John Kessenich426394d2015-07-23 10:22:48 -06002788 break;
2789 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002790 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002791 break;
2792 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002793 if (invertedType)
2794 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002795 }
2796
2797 if (noReturnValue)
2798 return false;
2799
2800 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002801 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002802 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002803 } else {
2804 builder.clearAccessChain();
2805 builder.setAccessChainRValue(result);
2806 return false;
2807 }
2808}
2809
John Kessenich433e9ff2017-01-26 20:31:11 -07002810// This path handles both if-then-else and ?:
2811// The if-then-else has a node type of void, while
2812// ?: has either a void or a non-void node type
2813//
2814// Leaving the result, when not void:
2815// GLSL only has r-values as the result of a :?, but
2816// if we have an l-value, that can be more efficient if it will
2817// become the base of a complex r-value expression, because the
2818// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002819bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2820{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002821 // see if OpSelect can handle it
2822 const auto isOpSelectable = [&]() {
2823 if (node->getBasicType() == glslang::EbtVoid)
2824 return false;
2825 // OpSelect can do all other types starting with SPV 1.4
2826 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2827 // pre-1.4, only scalars and vectors can be handled
2828 if ((!node->getType().isScalar() && !node->getType().isVector()))
2829 return false;
2830 }
2831 return true;
2832 };
2833
John Kessenich4bee5312018-02-20 21:29:05 -07002834 // See if it simple and safe, or required, to execute both sides.
2835 // Crucially, side effects must be either semantically required or avoided,
2836 // and there are performance trade-offs.
2837 // Return true if required or a good idea (and safe) to execute both sides,
2838 // false otherwise.
2839 const auto bothSidesPolicy = [&]() -> bool {
2840 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002841 if (node->getTrueBlock() == nullptr ||
2842 node->getFalseBlock() == nullptr)
2843 return false;
2844
John Kessenich4bee5312018-02-20 21:29:05 -07002845 // required? (unless we write additional code to look for side effects
2846 // and make performance trade-offs if none are present)
2847 if (!node->getShortCircuit())
2848 return true;
2849
2850 // if not required to execute both, decide based on performance/practicality...
2851
John Kessenich0c1e71a2019-01-10 18:23:06 +07002852 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002853 return false;
2854
John Kessenich433e9ff2017-01-26 20:31:11 -07002855 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2856 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2857
2858 // return true if a single operand to ? : is okay for OpSelect
2859 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002860 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002861 };
2862
2863 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2864 operandOkay(node->getFalseBlock()->getAsTyped());
2865 };
2866
John Kessenich4bee5312018-02-20 21:29:05 -07002867 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2868 // emit the condition before doing anything with selection
2869 node->getCondition()->traverse(this);
2870 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2871
2872 // Find a way of executing both sides and selecting the right result.
2873 const auto executeBothSides = [&]() -> void {
2874 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002875 node->getTrueBlock()->traverse(this);
2876 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2877 node->getFalseBlock()->traverse(this);
2878 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2879
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002880 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002881
John Kessenich4bee5312018-02-20 21:29:05 -07002882 // done if void
2883 if (node->getBasicType() == glslang::EbtVoid)
2884 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002885
John Kessenich4bee5312018-02-20 21:29:05 -07002886 // emit code to select between trueValue and falseValue
2887
2888 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002889 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002890 // Emit OpSelect for this selection.
2891
2892 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002893 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2894 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002895 condition = builder.smearScalar(spv::NoPrecision, condition,
2896 builder.makeVectorType(builder.makeBoolType(),
2897 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002898 }
John Kessenich4bee5312018-02-20 21:29:05 -07002899
2900 // OpSelect
2901 result = builder.createTriOp(spv::OpSelect,
2902 convertGlslangToSpvType(node->getType()), condition,
2903 trueValue, falseValue);
2904
2905 builder.clearAccessChain();
2906 builder.setAccessChainRValue(result);
2907 } else {
2908 // We need control flow to select the result.
2909 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2910 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2911
2912 // Selection control:
2913 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2914
2915 // make an "if" based on the value created by the condition
2916 spv::Builder::If ifBuilder(condition, control, builder);
2917
2918 // emit the "then" statement
2919 builder.createStore(trueValue, result);
2920 ifBuilder.makeBeginElse();
2921 // emit the "else" statement
2922 builder.createStore(falseValue, result);
2923
2924 // finish off the control flow
2925 ifBuilder.makeEndIf();
2926
2927 builder.clearAccessChain();
2928 builder.setAccessChainLValue(result);
2929 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002930 };
2931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 // Execute the one side needed, as per the condition
2933 const auto executeOneSide = [&]() {
2934 // Always emit control flow.
2935 if (node->getBasicType() != glslang::EbtVoid)
2936 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002937
John Kessenich4bee5312018-02-20 21:29:05 -07002938 // Selection control:
2939 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2940
2941 // make an "if" based on the value created by the condition
2942 spv::Builder::If ifBuilder(condition, control, builder);
2943
2944 // emit the "then" statement
2945 if (node->getTrueBlock() != nullptr) {
2946 node->getTrueBlock()->traverse(this);
2947 if (result != spv::NoResult)
2948 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2949 }
2950
2951 if (node->getFalseBlock() != nullptr) {
2952 ifBuilder.makeBeginElse();
2953 // emit the "else" statement
2954 node->getFalseBlock()->traverse(this);
2955 if (result != spv::NoResult)
2956 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2957 }
2958
2959 // finish off the control flow
2960 ifBuilder.makeEndIf();
2961
2962 if (result != spv::NoResult) {
2963 builder.clearAccessChain();
2964 builder.setAccessChainLValue(result);
2965 }
2966 };
2967
2968 // Try for OpSelect (or a requirement to execute both sides)
2969 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002970 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2971 if (node->getType().getQualifier().isSpecConstant())
2972 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002973 executeBothSides();
2974 } else
2975 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002976
2977 return false;
2978}
2979
2980bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2981{
2982 // emit and get the condition before doing anything with switch
2983 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002984 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002985
Rex Xu57e65922017-07-04 23:23:40 +08002986 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002987 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002988
John Kessenich140f3df2015-06-26 16:58:36 -06002989 // browse the children to sort out code segments
2990 int defaultSegment = -1;
2991 std::vector<TIntermNode*> codeSegments;
2992 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2993 std::vector<int> caseValues;
2994 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2995 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2996 TIntermNode* child = *c;
2997 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002998 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002999 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003000 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003001 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3002 } else
3003 codeSegments.push_back(child);
3004 }
3005
qining25262b32016-05-06 17:25:16 -04003006 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003007 // statements between the last case and the end of the switch statement
3008 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3009 (int)codeSegments.size() == defaultSegment)
3010 codeSegments.push_back(nullptr);
3011
3012 // make the switch statement
3013 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003014 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003015
3016 // emit all the code in the segments
3017 breakForLoop.push(false);
3018 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3019 builder.nextSwitchSegment(segmentBlocks, s);
3020 if (codeSegments[s])
3021 codeSegments[s]->traverse(this);
3022 else
3023 builder.addSwitchBreak();
3024 }
3025 breakForLoop.pop();
3026
3027 builder.endSwitch(segmentBlocks);
3028
3029 return false;
3030}
3031
3032void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3033{
3034 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003035 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003036
3037 builder.clearAccessChain();
3038 builder.setAccessChainRValue(constant);
3039}
3040
3041bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3042{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003043 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003044 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003045
3046 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003047 std::vector<unsigned int> operands;
3048 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003049
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003050 // Spec requires back edges to target header blocks, and every header block
3051 // must dominate its merge block. Make a header block first to ensure these
3052 // conditions are met. By definition, it will contain OpLoopMerge, followed
3053 // by a block-ending branch. But we don't want to put any other body/test
3054 // instructions in it, since the body/test may have arbitrary instructions,
3055 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003056 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003057 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003058 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003059 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003060 spv::Block& test = builder.makeNewBlock();
3061 builder.createBranch(&test);
3062
3063 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003064 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003065 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003066 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3067
3068 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003069 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003070 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003071 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003072 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003073 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003074
3075 builder.setBuildPoint(&blocks.continue_target);
3076 if (node->getTerminal())
3077 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003078 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003079 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003080 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003081 builder.createBranch(&blocks.body);
3082
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003083 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003084 builder.setBuildPoint(&blocks.body);
3085 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003086 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003087 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003088 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003089
3090 builder.setBuildPoint(&blocks.continue_target);
3091 if (node->getTerminal())
3092 node->getTerminal()->traverse(this);
3093 if (node->getTest()) {
3094 node->getTest()->traverse(this);
3095 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003096 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003097 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003098 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003099 // TODO: unless there was a break/return/discard instruction
3100 // somewhere in the body, this is an infinite loop, so we should
3101 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003102 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003103 }
John Kessenich140f3df2015-06-26 16:58:36 -06003104 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003105 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003106 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003107 return false;
3108}
3109
3110bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3111{
3112 if (node->getExpression())
3113 node->getExpression()->traverse(this);
3114
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003115 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003116
John Kessenich140f3df2015-06-26 16:58:36 -06003117 switch (node->getFlowOp()) {
3118 case glslang::EOpKill:
3119 builder.makeDiscard();
3120 break;
3121 case glslang::EOpBreak:
3122 if (breakForLoop.top())
3123 builder.createLoopExit();
3124 else
3125 builder.addSwitchBreak();
3126 break;
3127 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003128 builder.createLoopContinue();
3129 break;
3130 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003131 if (node->getExpression()) {
3132 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3133 spv::Id returnId = accessChainLoad(glslangReturnType);
3134 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3135 builder.clearAccessChain();
3136 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3137 builder.setAccessChainLValue(copyId);
3138 multiTypeStore(glslangReturnType, returnId);
3139 returnId = builder.createLoad(copyId);
3140 }
3141 builder.makeReturn(false, returnId);
3142 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003143 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003144
3145 builder.clearAccessChain();
3146 break;
3147
3148 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 }
3152
3153 return false;
3154}
3155
John Kessenich9c14f772019-06-17 08:38:35 -06003156spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003157{
qining25262b32016-05-06 17:25:16 -04003158 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003159 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003160 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003161 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003162 spv::Id result = createSpvConstant(*node);
3163 if (result != spv::NoResult)
3164 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 }
3166
3167 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003168 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003169 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3170 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003171
Rex Xucabbb782017-03-24 13:41:14 +08003172 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3173 node->getType().containsBasicType(glslang::EbtInt16) ||
3174 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003175 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003176 switch (storageClass) {
3177 case spv::StorageClassInput:
3178 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003179 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003180 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003181 break;
3182 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003183 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003184 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003185 break;
3186 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003187 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003188 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3189 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003190 else
3191 builder.addCapability(spv::CapabilityStorageUniform16);
3192 break;
3193 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003194 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003195 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3196 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3197 break;
3198 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003199 if (node->getType().containsBasicType(glslang::EbtFloat16))
3200 builder.addCapability(spv::CapabilityFloat16);
3201 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3202 node->getType().containsBasicType(glslang::EbtUint16))
3203 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003204 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003205 }
3206 }
Rex Xuf89ad982017-04-07 23:22:33 +08003207
John Kessenich312dcfb2018-07-03 13:19:51 -06003208 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3209 node->getType().containsBasicType(glslang::EbtUint8);
3210 if (contains8BitType) {
3211 if (storageClass == spv::StorageClassPushConstant) {
3212 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3213 builder.addCapability(spv::CapabilityStoragePushConstant8);
3214 } else if (storageClass == spv::StorageClassUniform) {
3215 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3216 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003217 } else if (storageClass == spv::StorageClassStorageBuffer) {
3218 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3219 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003220 } else {
3221 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003222 }
3223 }
3224
John Kessenich140f3df2015-06-26 16:58:36 -06003225 const char* name = node->getName().c_str();
3226 if (glslang::IsAnonymous(name))
3227 name = "";
3228
3229 return builder.createVariable(storageClass, spvType, name);
3230}
3231
3232// Return type Id of the sampled type.
3233spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3234{
3235 switch (sampler.type) {
3236 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003237#ifdef AMD_EXTENSIONS
3238 case glslang::EbtFloat16:
3239 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3240 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3241 return builder.makeFloatType(16);
3242#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003243 case glslang::EbtInt: return builder.makeIntType(32);
3244 case glslang::EbtUint: return builder.makeUintType(32);
3245 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 return builder.makeFloatType(32);
3248 }
3249}
3250
John Kessenich8c8505c2016-07-26 12:50:38 -06003251// If node is a swizzle operation, return the type that should be used if
3252// the swizzle base is first consumed by another operation, before the swizzle
3253// is applied.
3254spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3255{
John Kessenichecba76f2017-01-06 00:34:48 -07003256 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003257 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3258 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3259 else
3260 return spv::NoType;
3261}
3262
3263// When inverting a swizzle with a parent op, this function
3264// will apply the swizzle operation to a completed parent operation.
3265spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3266{
3267 std::vector<unsigned> swizzle;
3268 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3269 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3270}
3271
John Kessenich8c8505c2016-07-26 12:50:38 -06003272// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3273void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3274{
3275 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3276 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3277 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3278}
3279
John Kessenich3ac051e2015-12-20 11:29:16 -07003280// Convert from a glslang type to an SPV type, by calling into a
3281// recursive version of this function. This establishes the inherited
3282// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003283spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003284{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003285 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003286}
3287
3288// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003289// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003290// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003291spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003292 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3293 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003294{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003295 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003296
3297 switch (type.getBasicType()) {
3298 case glslang::EbtVoid:
3299 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003300 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
3302 case glslang::EbtFloat:
3303 spvType = builder.makeFloatType(32);
3304 break;
3305 case glslang::EbtDouble:
3306 spvType = builder.makeFloatType(64);
3307 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003308 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003309 spvType = builder.makeFloatType(16);
3310 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003311 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003312 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3313 // a 32-bit int where non-0 means true.
3314 if (explicitLayout != glslang::ElpNone)
3315 spvType = builder.makeUintType(32);
3316 else
3317 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003319 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003320 spvType = builder.makeIntType(8);
3321 break;
3322 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003323 spvType = builder.makeUintType(8);
3324 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003325 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003326 spvType = builder.makeIntType(16);
3327 break;
3328 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003329 spvType = builder.makeUintType(16);
3330 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003331 case glslang::EbtInt:
3332 spvType = builder.makeIntType(32);
3333 break;
3334 case glslang::EbtUint:
3335 spvType = builder.makeUintType(32);
3336 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003337 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 spvType = builder.makeIntType(64);
3339 break;
3340 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003341 spvType = builder.makeUintType(64);
3342 break;
John Kessenich426394d2015-07-23 10:22:48 -06003343 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003344 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003345 spvType = builder.makeUintType(32);
3346 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003347#ifdef NV_EXTENSIONS
3348 case glslang::EbtAccStructNV:
3349 spvType = builder.makeAccelerationStructureNVType();
3350 break;
3351#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003352 case glslang::EbtSampler:
3353 {
3354 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003355 if (sampler.sampler) {
3356 // pure sampler
3357 spvType = builder.makeSamplerType();
3358 } else {
3359 // an image is present, make its type
3360 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3361 sampler.image ? 2 : 1, TranslateImageFormat(type));
3362 if (sampler.combined) {
3363 // already has both image and sampler, make the combined type
3364 spvType = builder.makeSampledImageType(spvType);
3365 }
John Kessenich55e7d112015-11-15 21:33:39 -07003366 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003367 }
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369 case glslang::EbtStruct:
3370 case glslang::EbtBlock:
3371 {
3372 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003373 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003374
3375 // Try to share structs for different layouts, but not yet for other
3376 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003377 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003378 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003379 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
3381
3382 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003383 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003384 memberRemapper[glslangMembers].resize(glslangMembers->size());
3385 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003386 }
3387 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003388 case glslang::EbtReference:
3389 {
3390 // Make the forward pointer, then recurse to convert the structure type, then
3391 // patch up the forward pointer with a real pointer type.
3392 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3393 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3394 forwardPointers[type.getReferentType()] = forwardId;
3395 }
3396 spvType = forwardPointers[type.getReferentType()];
3397 if (!forwardReferenceOnly) {
3398 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3399 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3400 forwardPointers[type.getReferentType()],
3401 referentType);
3402 }
3403 }
3404 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003405 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003406 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 }
3409
3410 if (type.isMatrix())
3411 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3412 else {
3413 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3414 if (type.getVectorSize() > 1)
3415 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3416 }
3417
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003418 if (type.isCoopMat()) {
3419 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3420 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3421 if (type.getBasicType() == glslang::EbtFloat16)
3422 builder.addCapability(spv::CapabilityFloat16);
3423
3424 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3425 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3426 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3427
3428 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3429 }
3430
John Kessenich140f3df2015-06-26 16:58:36 -06003431 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003432 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3433
John Kessenichc9a80832015-09-12 12:17:44 -06003434 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003435 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003436 // We need to decorate array strides for types needing explicit layout, except blocks.
3437 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003438 // Use a dummy glslang type for querying internal strides of
3439 // arrays of arrays, but using just a one-dimensional array.
3440 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003441 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3442 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003443
3444 // Will compute the higher-order strides here, rather than making a whole
3445 // pile of types and doing repetitive recursion on their contents.
3446 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3447 }
John Kessenichf8842e52016-01-04 19:22:56 -07003448
3449 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003450 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003451 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003452 if (stride > 0)
3453 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003454 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003455 }
3456 } else {
3457 // single-dimensional array, and don't yet have stride
3458
John Kessenichf8842e52016-01-04 19:22:56 -07003459 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003460 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3461 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003462 }
John Kessenich31ed4832015-09-09 17:51:38 -06003463
John Kessenichead86222018-03-28 18:01:20 -06003464 // Do the outer dimension, which might not be known for a runtime-sized array.
3465 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3466 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003468 else {
3469 if (!lastBufferBlockMember) {
3470 builder.addExtension("SPV_EXT_descriptor_indexing");
3471 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3472 }
John Kessenichead86222018-03-28 18:01:20 -06003473 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003474 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003475 if (stride > 0)
3476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 }
3478
3479 return spvType;
3480}
3481
John Kessenich0e737842017-03-24 18:38:16 -06003482// TODO: this functionality should exist at a higher level, in creating the AST
3483//
3484// Identify interface members that don't have their required extension turned on.
3485//
3486bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3487{
Chao Chen3c366992018-09-19 11:41:59 -07003488#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003489 auto& extensions = glslangIntermediate->getRequestedExtensions();
3490
Rex Xubcf291a2017-03-29 23:01:36 +08003491 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3492 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3493 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003494 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3495 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3496 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003497
3498 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3499 if (member.getFieldName() == "gl_ViewportMask" &&
3500 extensions.find("GL_NV_viewport_array2") == extensions.end())
3501 return true;
3502 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3504 return true;
3505 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3506 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3507 return true;
3508 }
3509#endif
John Kessenich0e737842017-03-24 18:38:16 -06003510
3511 return false;
3512};
3513
John Kessenich6090df02016-06-30 21:18:02 -06003514// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3515// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3516// Mutually recursive with convertGlslangToSpvType().
3517spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3518 const glslang::TTypeList* glslangMembers,
3519 glslang::TLayoutPacking explicitLayout,
3520 const glslang::TQualifier& qualifier)
3521{
3522 // Create a vector of struct types for SPIR-V to consume
3523 std::vector<spv::Id> spvMembers;
3524 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 -06003525 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003526 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3527 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3528 if (glslangMember.hiddenMember()) {
3529 ++memberDelta;
3530 if (type.getBasicType() == glslang::EbtBlock)
3531 memberRemapper[glslangMembers][i] = -1;
3532 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003533 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003534 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003535 if (filterMember(glslangMember))
3536 continue;
3537 }
John Kessenich6090df02016-06-30 21:18:02 -06003538 // modify just this child's view of the qualifier
3539 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3540 InheritQualifiers(memberQualifier, qualifier);
3541
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003542 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003543 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003544 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003545
3546 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003547 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3548 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003549
3550 // Make forward pointers for any pointer members, and create a list of members to
3551 // convert to spirv types after creating the struct.
3552 if (glslangMember.getBasicType() == glslang::EbtReference) {
3553 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3554 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3555 }
3556 spvMembers.push_back(
3557 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3558 } else {
3559 spvMembers.push_back(
3560 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3561 }
John Kessenich6090df02016-06-30 21:18:02 -06003562 }
3563 }
3564
3565 // Make the SPIR-V type
3566 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003567 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003568 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3569
3570 // Decorate it
3571 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3572
John Kessenichd72f4882019-01-16 14:55:37 +07003573 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003574 auto it = deferredForwardPointers[i];
3575 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3576 }
3577
John Kessenich6090df02016-06-30 21:18:02 -06003578 return spvType;
3579}
3580
3581void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3582 const glslang::TTypeList* glslangMembers,
3583 glslang::TLayoutPacking explicitLayout,
3584 const glslang::TQualifier& qualifier,
3585 spv::Id spvType)
3586{
3587 // Name and decorate the non-hidden members
3588 int offset = -1;
3589 int locationOffset = 0; // for use within the members of this struct
3590 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3591 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3592 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003593 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003594 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003595 if (filterMember(glslangMember))
3596 continue;
3597 }
John Kessenich6090df02016-06-30 21:18:02 -06003598
3599 // modify just this child's view of the qualifier
3600 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3601 InheritQualifiers(memberQualifier, qualifier);
3602
3603 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003604 if (member < 0)
3605 continue;
3606
3607 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3608 builder.addMemberDecoration(spvType, member,
3609 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3610 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3611 // Add interpolation and auxiliary storage decorations only to
3612 // top-level members of Input and Output storage classes
3613 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3614 type.getQualifier().storage == glslang::EvqVaryingOut) {
3615 if (type.getBasicType() == glslang::EbtBlock ||
3616 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3617 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3618 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003619#ifdef NV_EXTENSIONS
3620 addMeshNVDecoration(spvType, member, memberQualifier);
3621#endif
John Kessenich6090df02016-06-30 21:18:02 -06003622 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003623 }
3624 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003625
John Kessenich5d610ee2018-03-07 18:05:55 -07003626 if (type.getBasicType() == glslang::EbtBlock &&
3627 qualifier.storage == glslang::EvqBuffer) {
3628 // Add memory decorations only to top-level members of shader storage block
3629 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003630 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003631 for (unsigned int i = 0; i < memory.size(); ++i)
3632 builder.addMemberDecoration(spvType, member, memory[i]);
3633 }
John Kessenich6090df02016-06-30 21:18:02 -06003634
John Kessenich5d610ee2018-03-07 18:05:55 -07003635 // Location assignment was already completed correctly by the front end,
3636 // just track whether a member needs to be decorated.
3637 // Ignore member locations if the container is an array, as that's
3638 // ill-specified and decisions have been made to not allow this.
3639 if (! type.isArray() && memberQualifier.hasLocation())
3640 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003641
John Kessenich5d610ee2018-03-07 18:05:55 -07003642 if (qualifier.hasLocation()) // track for upcoming inheritance
3643 locationOffset += glslangIntermediate->computeTypeLocationSize(
3644 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003645
John Kessenich5d610ee2018-03-07 18:05:55 -07003646 // component, XFB, others
3647 if (glslangMember.getQualifier().hasComponent())
3648 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3649 glslangMember.getQualifier().layoutComponent);
3650 if (glslangMember.getQualifier().hasXfbOffset())
3651 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3652 glslangMember.getQualifier().layoutXfbOffset);
3653 else if (explicitLayout != glslang::ElpNone) {
3654 // figure out what to do with offset, which is accumulating
3655 int nextOffset;
3656 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3657 if (offset >= 0)
3658 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3659 offset = nextOffset;
3660 }
John Kessenich6090df02016-06-30 21:18:02 -06003661
John Kessenich5d610ee2018-03-07 18:05:55 -07003662 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3663 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3664 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003665
John Kessenich5d610ee2018-03-07 18:05:55 -07003666 // built-in variable decorations
3667 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3668 if (builtIn != spv::BuiltInMax)
3669 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003670
John Kessenich5611c6d2018-04-05 11:25:02 -06003671 // nonuniform
3672 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3673
John Kessenichead86222018-03-28 18:01:20 -06003674 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3675 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3676 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3677 memberQualifier.semanticName);
3678 }
3679
chaoc771d89f2017-01-13 01:10:53 -08003680#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003681 if (builtIn == spv::BuiltInLayer) {
3682 // SPV_NV_viewport_array2 extension
3683 if (glslangMember.getQualifier().layoutViewportRelative){
3684 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3685 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3686 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003687 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003688 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3689 builder.addMemberDecoration(spvType, member,
3690 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3691 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3692 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3693 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003694 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003695 }
3696 if (glslangMember.getQualifier().layoutPassthrough) {
3697 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3698 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3699 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3700 }
chaoc771d89f2017-01-13 01:10:53 -08003701#endif
John Kessenich6090df02016-06-30 21:18:02 -06003702 }
3703
3704 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003705 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3706 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003707}
3708
John Kessenich6c292d32016-02-15 20:58:50 -07003709// Turn the expression forming the array size into an id.
3710// This is not quite trivial, because of specialization constants.
3711// Sometimes, a raw constant is turned into an Id, and sometimes
3712// a specialization constant expression is.
3713spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3714{
3715 // First, see if this is sized with a node, meaning a specialization constant:
3716 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3717 if (specNode != nullptr) {
3718 builder.clearAccessChain();
3719 specNode->traverse(this);
3720 return accessChainLoad(specNode->getAsTyped()->getType());
3721 }
qining25262b32016-05-06 17:25:16 -04003722
John Kessenich6c292d32016-02-15 20:58:50 -07003723 // Otherwise, need a compile-time (front end) size, get it:
3724 int size = arraySizes.getDimSize(dim);
3725 assert(size > 0);
3726 return builder.makeUintConstant(size);
3727}
3728
John Kessenich103bef92016-02-08 21:38:15 -07003729// Wrap the builder's accessChainLoad to:
3730// - localize handling of RelaxedPrecision
3731// - use the SPIR-V inferred type instead of another conversion of the glslang type
3732// (avoids unnecessary work and possible type punning for structures)
3733// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003734spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3735{
John Kessenich103bef92016-02-08 21:38:15 -07003736 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003737
3738 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3739 coherentFlags |= TranslateCoherent(type);
3740
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003741 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003742 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003743
John Kessenich5611c6d2018-04-05 11:25:02 -06003744 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003745 TranslateNonUniformDecoration(type.getQualifier()),
3746 nominalTypeId,
3747 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003748 TranslateMemoryScope(coherentFlags),
3749 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003750
3751 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003752 if (type.getBasicType() == glslang::EbtBool) {
3753 if (builder.isScalarType(nominalTypeId)) {
3754 // Conversion for bool
3755 spv::Id boolType = builder.makeBoolType();
3756 if (nominalTypeId != boolType)
3757 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3758 } else if (builder.isVectorType(nominalTypeId)) {
3759 // Conversion for bvec
3760 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3761 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3762 if (nominalTypeId != bvecType)
3763 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3764 }
3765 }
John Kessenich103bef92016-02-08 21:38:15 -07003766
3767 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003768}
3769
Rex Xu27253232016-02-23 17:51:09 +08003770// Wrap the builder's accessChainStore to:
3771// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003772//
3773// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003774void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3775{
3776 // Need to convert to abstract types when necessary
3777 if (type.getBasicType() == glslang::EbtBool) {
3778 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3779
3780 if (builder.isScalarType(nominalTypeId)) {
3781 // Conversion for bool
3782 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003783 if (nominalTypeId != boolType) {
3784 // keep these outside arguments, for determinant order-of-evaluation
3785 spv::Id one = builder.makeUintConstant(1);
3786 spv::Id zero = builder.makeUintConstant(0);
3787 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3788 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003789 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003790 } else if (builder.isVectorType(nominalTypeId)) {
3791 // Conversion for bvec
3792 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3793 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003794 if (nominalTypeId != bvecType) {
3795 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003796 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3797 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3798 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003799 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003800 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3801 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003802 }
3803 }
3804
Jeff Bolz36831c92018-09-05 10:11:41 -05003805 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3806 coherentFlags |= TranslateCoherent(type);
3807
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003808 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003809 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003810
Jeff Bolz36831c92018-09-05 10:11:41 -05003811 builder.accessChainStore(rvalue,
3812 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003813 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003814}
3815
John Kessenich4bf71552016-09-02 11:20:21 -06003816// For storing when types match at the glslang level, but not might match at the
3817// SPIR-V level.
3818//
3819// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003820// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003821// as in a member-decorated way.
3822//
3823// NOTE: This function can handle any store request; if it's not special it
3824// simplifies to a simple OpStore.
3825//
3826// Implicitly uses the existing builder.accessChain as the storage target.
3827void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3828{
John Kessenichb3e24e42016-09-11 12:33:43 -06003829 // we only do the complex path here if it's an aggregate
3830 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003831 accessChainStore(type, rValue);
3832 return;
3833 }
3834
John Kessenichb3e24e42016-09-11 12:33:43 -06003835 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003836 spv::Id rType = builder.getTypeId(rValue);
3837 spv::Id lValue = builder.accessChainGetLValue();
3838 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3839 if (lType == rType) {
3840 accessChainStore(type, rValue);
3841 return;
3842 }
3843
John Kessenichb3e24e42016-09-11 12:33:43 -06003844 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003845 // where the two types were the same type in GLSL. This requires member
3846 // by member copy, recursively.
3847
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003848 // SPIR-V 1.4 added an instruction to do help do this.
3849 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3850 // However, bool in uniform space is changed to int, so
3851 // OpCopyLogical does not work for that.
3852 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3853 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3854 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3855 if (lBool == rBool) {
3856 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3857 accessChainStore(type, logicalCopy);
3858 return;
3859 }
3860 }
3861
John Kessenichb3e24e42016-09-11 12:33:43 -06003862 // If an array, copy element by element.
3863 if (type.isArray()) {
3864 glslang::TType glslangElementType(type, 0);
3865 spv::Id elementRType = builder.getContainedTypeId(rType);
3866 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3867 // get the source member
3868 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003869
John Kessenichb3e24e42016-09-11 12:33:43 -06003870 // set up the target storage
3871 builder.clearAccessChain();
3872 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003873 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003874
John Kessenichb3e24e42016-09-11 12:33:43 -06003875 // store the member
3876 multiTypeStore(glslangElementType, elementRValue);
3877 }
3878 } else {
3879 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003880
John Kessenichb3e24e42016-09-11 12:33:43 -06003881 // loop over structure members
3882 const glslang::TTypeList& members = *type.getStruct();
3883 for (int m = 0; m < (int)members.size(); ++m) {
3884 const glslang::TType& glslangMemberType = *members[m].type;
3885
3886 // get the source member
3887 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3888 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3889
3890 // set up the target storage
3891 builder.clearAccessChain();
3892 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003893 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003894
3895 // store the member
3896 multiTypeStore(glslangMemberType, memberRValue);
3897 }
John Kessenich4bf71552016-09-02 11:20:21 -06003898 }
3899}
3900
John Kessenichf85e8062015-12-19 13:57:10 -07003901// Decide whether or not this type should be
3902// decorated with offsets and strides, and if so
3903// whether std140 or std430 rules should be applied.
3904glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003905{
John Kessenichf85e8062015-12-19 13:57:10 -07003906 // has to be a block
3907 if (type.getBasicType() != glslang::EbtBlock)
3908 return glslang::ElpNone;
3909
Chao Chen3c366992018-09-19 11:41:59 -07003910 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003911 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003912 type.getQualifier().storage != glslang::EvqBuffer &&
3913 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003914 return glslang::ElpNone;
3915
3916 // return the layout to use
3917 switch (type.getQualifier().layoutPacking) {
3918 case glslang::ElpStd140:
3919 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003920 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003921 return type.getQualifier().layoutPacking;
3922 default:
3923 return glslang::ElpNone;
3924 }
John Kessenich31ed4832015-09-09 17:51:38 -06003925}
3926
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003927// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003928int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003929{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003930 int size;
John Kessenich49987892015-12-29 17:11:44 -07003931 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003932 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003933
3934 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003935}
3936
John Kessenich49987892015-12-29 17:11:44 -07003937// 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 -07003938// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003939int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003940{
John Kessenich49987892015-12-29 17:11:44 -07003941 glslang::TType elementType;
3942 elementType.shallowCopy(matrixType);
3943 elementType.clearArraySizes();
3944
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003945 int size;
John Kessenich49987892015-12-29 17:11:44 -07003946 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003947 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003948
3949 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003950}
3951
John Kessenich5e4b1242015-08-06 22:53:06 -06003952// Given a member type of a struct, realign the current offset for it, and compute
3953// the next (not yet aligned) offset for the next member, which will get aligned
3954// on the next call.
3955// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3956// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3957// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003958void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003959 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003960{
3961 // this will get a positive value when deemed necessary
3962 nextOffset = -1;
3963
John Kessenich5e4b1242015-08-06 22:53:06 -06003964 // override anything in currentOffset with user-set offset
3965 if (memberType.getQualifier().hasOffset())
3966 currentOffset = memberType.getQualifier().layoutOffset;
3967
3968 // It could be that current linker usage in glslang updated all the layoutOffset,
3969 // in which case the following code does not matter. But, that's not quite right
3970 // once cross-compilation unit GLSL validation is done, as the original user
3971 // settings are needed in layoutOffset, and then the following will come into play.
3972
John Kessenichf85e8062015-12-19 13:57:10 -07003973 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003974 if (! memberType.getQualifier().hasOffset())
3975 currentOffset = -1;
3976
3977 return;
3978 }
3979
John Kessenichf85e8062015-12-19 13:57:10 -07003980 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003981 if (currentOffset < 0)
3982 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003983
John Kessenich5e4b1242015-08-06 22:53:06 -06003984 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3985 // but possibly not yet correctly aligned.
3986
3987 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003988 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003989 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003990
3991 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003992 // TODO: make this consistent in early phases of code:
3993 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3994 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3995 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003996 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003997 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003998 int dummySize;
3999 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4000 if (componentAlignment <= 4)
4001 memberAlignment = componentAlignment;
4002 }
4003
4004 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004005 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004006
4007 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004008 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004009 glslang::RoundToPow2(currentOffset, 16);
4010
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 nextOffset = currentOffset + memberSize;
4012}
4013
David Netoa901ffe2016-06-08 14:11:40 +01004014void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004015{
David Netoa901ffe2016-06-08 14:11:40 +01004016 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4017 switch (glslangBuiltIn)
4018 {
4019 case glslang::EbvClipDistance:
4020 case glslang::EbvCullDistance:
4021 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08004022#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08004023 case glslang::EbvViewportMaskNV:
4024 case glslang::EbvSecondaryPositionNV:
4025 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004026 case glslang::EbvPositionPerViewNV:
4027 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004028 case glslang::EbvTaskCountNV:
4029 case glslang::EbvPrimitiveCountNV:
4030 case glslang::EbvPrimitiveIndicesNV:
4031 case glslang::EbvClipDistancePerViewNV:
4032 case glslang::EbvCullDistancePerViewNV:
4033 case glslang::EbvLayerPerViewNV:
4034 case glslang::EbvMeshViewCountNV:
4035 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004036#endif
David Netoa901ffe2016-06-08 14:11:40 +01004037 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4038 // Alternately, we could just call this for any glslang built-in, since the
4039 // capability already guards against duplicates.
4040 TranslateBuiltInDecoration(glslangBuiltIn, false);
4041 break;
4042 default:
4043 // Capabilities were already generated when the struct was declared.
4044 break;
4045 }
John Kessenichebb50532016-05-16 19:22:05 -06004046}
4047
John Kessenich6fccb3c2016-09-19 16:01:41 -06004048bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004049{
John Kessenicheee9d532016-09-19 18:09:30 -06004050 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004051}
4052
John Kessenichd41993d2017-09-10 15:21:05 -06004053// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004054// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4055// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004056bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004057{
John Kessenich6a14f782017-12-04 02:48:10 -07004058 assert(qualifier == glslang::EvqIn ||
4059 qualifier == glslang::EvqOut ||
4060 qualifier == glslang::EvqInOut ||
4061 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004062 return qualifier != glslang::EvqConstReadOnly;
4063}
4064
4065// Is parameter pass-by-original?
4066bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4067 bool implicitThisParam)
4068{
4069 if (implicitThisParam) // implicit this
4070 return true;
4071 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004072 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004073 return paramType.containsOpaque() || // sampler, etc.
4074 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4075}
4076
John Kessenich140f3df2015-06-26 16:58:36 -06004077// Make all the functions, skeletally, without actually visiting their bodies.
4078void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4079{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004080 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004081 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4082 if (paramPrecision != spv::NoPrecision)
4083 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004084 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004085 if (type.getBasicType() == glslang::EbtReference) {
4086 // Original and non-writable params pass the pointer directly and
4087 // use restrict/aliased, others are stored to a pointer in Function
4088 // memory and use RestrictPointer/AliasedPointer.
4089 if (originalParam(type.getQualifier().storage, type, false) ||
4090 !writableParam(type.getQualifier().storage)) {
4091 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4092 } else {
4093 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4094 }
4095 }
John Kessenichfad62972017-07-18 02:35:46 -06004096 };
4097
John Kessenich140f3df2015-06-26 16:58:36 -06004098 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4099 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004100 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004101 continue;
4102
4103 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004104 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004105 //
qining25262b32016-05-06 17:25:16 -04004106 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004107 // function. What it is an address of varies:
4108 //
John Kessenich4bf71552016-09-02 11:20:21 -06004109 // - "in" parameters not marked as "const" can be written to without modifying the calling
4110 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004111 //
4112 // - "const in" parameters can just be the r-value, as no writes need occur.
4113 //
John Kessenich4bf71552016-09-02 11:20:21 -06004114 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4115 // 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 -06004116
4117 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004118 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004119 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4120
John Kessenichfad62972017-07-18 02:35:46 -06004121 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4122 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004123
John Kessenichfad62972017-07-18 02:35:46 -06004124 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004125 for (int p = 0; p < (int)parameters.size(); ++p) {
4126 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4127 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004128 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004129 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004130 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004131 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4132 else
John Kessenich4bf71552016-09-02 11:20:21 -06004133 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004134 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004135 paramTypes.push_back(typeId);
4136 }
4137
4138 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004139 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4140 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004141 glslFunction->getName().c_str(), paramTypes,
4142 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004143 if (implicitThis)
4144 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004145
4146 // Track function to emit/call later
4147 functionMap[glslFunction->getName().c_str()] = function;
4148
4149 // Set the parameter id's
4150 for (int p = 0; p < (int)parameters.size(); ++p) {
4151 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4152 // give a name too
4153 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004154
4155 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4156 if (paramType.containsBasicType(glslang::EbtInt8) ||
4157 paramType.containsBasicType(glslang::EbtUint8))
4158 builder.addCapability(spv::CapabilityInt8);
4159 if (paramType.containsBasicType(glslang::EbtInt16) ||
4160 paramType.containsBasicType(glslang::EbtUint16))
4161 builder.addCapability(spv::CapabilityInt16);
4162 if (paramType.containsBasicType(glslang::EbtFloat16))
4163 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004164 }
4165 }
4166}
4167
4168// Process all the initializers, while skipping the functions and link objects
4169void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4170{
4171 builder.setBuildPoint(shaderEntry->getLastBlock());
4172 for (int i = 0; i < (int)initializers.size(); ++i) {
4173 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4174 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4175
4176 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004177 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004178 initializer->traverse(this);
4179 }
4180 }
4181}
4182
4183// Process all the functions, while skipping initializers.
4184void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4185{
4186 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4187 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004188 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004189 node->traverse(this);
4190 }
4191}
4192
4193void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4194{
qining25262b32016-05-06 17:25:16 -04004195 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004196 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004197 currentFunction = functionMap[node->getName().c_str()];
4198 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004199 builder.setBuildPoint(functionBlock);
4200}
4201
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004202void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004203{
Rex Xufc618912015-09-09 16:42:49 +08004204 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004205
4206 glslang::TSampler sampler = {};
4207 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004208#ifdef AMD_EXTENSIONS
4209 bool f16ShadowCompare = false;
4210#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004211 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004212 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4213 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004214#ifdef AMD_EXTENSIONS
4215 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4216#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004217 }
4218
John Kessenich140f3df2015-06-26 16:58:36 -06004219 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4220 builder.clearAccessChain();
4221 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004222
4223 // Special case l-value operands
4224 bool lvalue = false;
4225 switch (node.getOp()) {
4226 case glslang::EOpImageAtomicAdd:
4227 case glslang::EOpImageAtomicMin:
4228 case glslang::EOpImageAtomicMax:
4229 case glslang::EOpImageAtomicAnd:
4230 case glslang::EOpImageAtomicOr:
4231 case glslang::EOpImageAtomicXor:
4232 case glslang::EOpImageAtomicExchange:
4233 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004234 case glslang::EOpImageAtomicLoad:
4235 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004236 if (i == 0)
4237 lvalue = true;
4238 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004239 case glslang::EOpSparseImageLoad:
4240 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4241 lvalue = true;
4242 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004243#ifdef AMD_EXTENSIONS
4244 case glslang::EOpSparseTexture:
4245 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4246 lvalue = true;
4247 break;
4248 case glslang::EOpSparseTextureClamp:
4249 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4250 lvalue = true;
4251 break;
4252 case glslang::EOpSparseTextureLod:
4253 case glslang::EOpSparseTextureOffset:
4254 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4255 lvalue = true;
4256 break;
4257#else
Rex Xu48edadf2015-12-31 16:11:41 +08004258 case glslang::EOpSparseTexture:
4259 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4260 lvalue = true;
4261 break;
4262 case glslang::EOpSparseTextureClamp:
4263 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4264 lvalue = true;
4265 break;
4266 case glslang::EOpSparseTextureLod:
4267 case glslang::EOpSparseTextureOffset:
4268 if (i == 3)
4269 lvalue = true;
4270 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004271#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004272 case glslang::EOpSparseTextureFetch:
4273 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4274 lvalue = true;
4275 break;
4276 case glslang::EOpSparseTextureFetchOffset:
4277 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4278 lvalue = true;
4279 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004280#ifdef AMD_EXTENSIONS
4281 case glslang::EOpSparseTextureLodOffset:
4282 case glslang::EOpSparseTextureGrad:
4283 case glslang::EOpSparseTextureOffsetClamp:
4284 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4285 lvalue = true;
4286 break;
4287 case glslang::EOpSparseTextureGradOffset:
4288 case glslang::EOpSparseTextureGradClamp:
4289 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4290 lvalue = true;
4291 break;
4292 case glslang::EOpSparseTextureGradOffsetClamp:
4293 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4294 lvalue = true;
4295 break;
4296#else
Rex Xu48edadf2015-12-31 16:11:41 +08004297 case glslang::EOpSparseTextureLodOffset:
4298 case glslang::EOpSparseTextureGrad:
4299 case glslang::EOpSparseTextureOffsetClamp:
4300 if (i == 4)
4301 lvalue = true;
4302 break;
4303 case glslang::EOpSparseTextureGradOffset:
4304 case glslang::EOpSparseTextureGradClamp:
4305 if (i == 5)
4306 lvalue = true;
4307 break;
4308 case glslang::EOpSparseTextureGradOffsetClamp:
4309 if (i == 6)
4310 lvalue = true;
4311 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004312#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004313 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004314 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4315 lvalue = true;
4316 break;
4317 case glslang::EOpSparseTextureGatherOffset:
4318 case glslang::EOpSparseTextureGatherOffsets:
4319 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4320 lvalue = true;
4321 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004322#ifdef AMD_EXTENSIONS
4323 case glslang::EOpSparseTextureGatherLod:
4324 if (i == 3)
4325 lvalue = true;
4326 break;
4327 case glslang::EOpSparseTextureGatherLodOffset:
4328 case glslang::EOpSparseTextureGatherLodOffsets:
4329 if (i == 4)
4330 lvalue = true;
4331 break;
Rex Xu129799a2017-07-05 17:23:28 +08004332 case glslang::EOpSparseImageLoadLod:
4333 if (i == 3)
4334 lvalue = true;
4335 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004336#endif
Chao Chen3a137962018-09-19 11:41:27 -07004337#ifdef NV_EXTENSIONS
4338 case glslang::EOpImageSampleFootprintNV:
4339 if (i == 4)
4340 lvalue = true;
4341 break;
4342 case glslang::EOpImageSampleFootprintClampNV:
4343 case glslang::EOpImageSampleFootprintLodNV:
4344 if (i == 5)
4345 lvalue = true;
4346 break;
4347 case glslang::EOpImageSampleFootprintGradNV:
4348 if (i == 6)
4349 lvalue = true;
4350 break;
4351 case glslang::EOpImageSampleFootprintGradClampNV:
4352 if (i == 7)
4353 lvalue = true;
4354 break;
4355#endif
Rex Xufc618912015-09-09 16:42:49 +08004356 default:
4357 break;
4358 }
4359
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004360 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004361 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004362 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4363 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4364 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004365 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004366 }
4367}
4368
John Kessenichfc51d282015-08-19 13:34:18 -06004369void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004370{
John Kessenichfc51d282015-08-19 13:34:18 -06004371 builder.clearAccessChain();
4372 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004373 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004374}
John Kessenich140f3df2015-06-26 16:58:36 -06004375
John Kessenichfc51d282015-08-19 13:34:18 -06004376spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4377{
John Kesseniche485c7a2017-05-31 18:50:53 -06004378 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004379 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004380
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004381 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004382
John Kessenichfc51d282015-08-19 13:34:18 -06004383 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004384
John Kessenichf43c7392019-03-31 10:51:57 -06004385 const glslang::TType &imageType = node->getAsAggregate()
4386 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4387 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004388 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004389#ifdef AMD_EXTENSIONS
4390 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004391 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4392 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004393#endif
4394
John Kessenichf43c7392019-03-31 10:51:57 -06004395 const auto signExtensionMask = [&]() {
4396 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4397 if (sampler.type == glslang::EbtUint)
4398 return spv::ImageOperandsZeroExtendMask;
4399 else if (sampler.type == glslang::EbtInt)
4400 return spv::ImageOperandsSignExtendMask;
4401 }
4402 return spv::ImageOperandsMaskNone;
4403 };
4404
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004405 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4406
John Kessenichfc51d282015-08-19 13:34:18 -06004407 std::vector<spv::Id> arguments;
4408 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004409 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004410 else
4411 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004412 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004413
4414 spv::Builder::TextureParameters params = { };
4415 params.sampler = arguments[0];
4416
Rex Xu04db3f52015-09-16 11:44:02 +08004417 glslang::TCrackedTextureOp cracked;
4418 node->crackTexture(sampler, cracked);
4419
amhagan05506bb2017-06-13 16:53:02 -04004420 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004421
John Kessenichfc51d282015-08-19 13:34:18 -06004422 // Check for queries
4423 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004424 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4425 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004426 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004427
John Kessenichfc51d282015-08-19 13:34:18 -06004428 switch (node->getOp()) {
4429 case glslang::EOpImageQuerySize:
4430 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004431 if (arguments.size() > 1) {
4432 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004433 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004434 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004435 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004436 case glslang::EOpImageQuerySamples:
4437 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004438 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004439 case glslang::EOpTextureQueryLod:
4440 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004441 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004442 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004443 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004444 case glslang::EOpSparseTexelsResident:
4445 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004446 default:
4447 assert(0);
4448 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004449 }
John Kessenich140f3df2015-06-26 16:58:36 -06004450 }
4451
LoopDawg4425f242018-02-18 11:40:01 -07004452 int components = node->getType().getVectorSize();
4453
4454 if (node->getOp() == glslang::EOpTextureFetch) {
4455 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4456 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4457 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4458 // here around e.g. which ones return scalars or other types.
4459 components = 4;
4460 }
4461
4462 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4463
4464 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4465
Rex Xufc618912015-09-09 16:42:49 +08004466 // Check for image functions other than queries
4467 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004468 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004469 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004470 spv::IdImmediate image = { true, *(opIt++) };
4471 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004472
4473 // Handle subpass operations
4474 // TODO: GLSL should change to have the "MS" only on the type rather than the
4475 // built-in function.
4476 if (cracked.subpass) {
4477 // add on the (0,0) coordinate
4478 spv::Id zero = builder.makeIntConstant(0);
4479 std::vector<spv::Id> comps;
4480 comps.push_back(zero);
4481 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004482 spv::IdImmediate coord = { true,
4483 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4484 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004485 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4486 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004487 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004488 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4489 }
4490 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004491 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004492 if (sampler.ms) {
4493 spv::IdImmediate imageOperand = { true, *(opIt++) };
4494 operands.push_back(imageOperand);
4495 }
John Kessenich6c292d32016-02-15 20:58:50 -07004496 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004497 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4498 builder.setPrecision(result, precision);
4499 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004500 }
4501
John Kessenich149afc32018-08-14 13:31:43 -06004502 spv::IdImmediate coord = { true, *(opIt++) };
4503 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004504#ifdef AMD_EXTENSIONS
4505 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4506#else
John Kessenich56bab042015-09-16 10:54:31 -06004507 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004508#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004509 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004510 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004511 mask = mask | spv::ImageOperandsSampleMask;
4512 }
Rex Xu129799a2017-07-05 17:23:28 +08004513#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004514 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004515 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4516 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004517 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004518 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004519#endif
4520 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4521 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004522 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004523 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004524 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4525 operands.push_back(imageOperands);
4526 }
4527 if (mask & spv::ImageOperandsSampleMask) {
4528 spv::IdImmediate imageOperand = { true, *opIt++ };
4529 operands.push_back(imageOperand);
4530 }
4531#ifdef AMD_EXTENSIONS
4532 if (mask & spv::ImageOperandsLodMask) {
4533 spv::IdImmediate imageOperand = { true, *opIt++ };
4534 operands.push_back(imageOperand);
4535 }
4536#endif
4537 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004538 spv::IdImmediate imageOperand = { true,
4539 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004540 operands.push_back(imageOperand);
4541 }
4542
John Kessenich149afc32018-08-14 13:31:43 -06004543 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004544 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004545
John Kessenich149afc32018-08-14 13:31:43 -06004546 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004547 builder.setPrecision(result[0], precision);
4548
4549 // If needed, add a conversion constructor to the proper size.
4550 if (components != node->getType().getVectorSize())
4551 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4552
4553 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004554#ifdef AMD_EXTENSIONS
4555 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4556#else
John Kessenich56bab042015-09-16 10:54:31 -06004557 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004558#endif
Rex Xu129799a2017-07-05 17:23:28 +08004559
Jeff Bolz36831c92018-09-05 10:11:41 -05004560 // Push the texel value before the operands
4561#ifdef AMD_EXTENSIONS
4562 if (sampler.ms || cracked.lod) {
4563#else
4564 if (sampler.ms) {
4565#endif
John Kessenich149afc32018-08-14 13:31:43 -06004566 spv::IdImmediate texel = { true, *(opIt + 1) };
4567 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004568 } else {
4569 spv::IdImmediate texel = { true, *opIt };
4570 operands.push_back(texel);
4571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572
4573 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4574 if (sampler.ms) {
4575 mask = mask | spv::ImageOperandsSampleMask;
4576 }
4577#ifdef AMD_EXTENSIONS
4578 if (cracked.lod) {
4579 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4580 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4581 mask = mask | spv::ImageOperandsLodMask;
4582 }
4583#endif
4584 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4585 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004586 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004587 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4589 operands.push_back(imageOperands);
4590 }
4591 if (mask & spv::ImageOperandsSampleMask) {
4592 spv::IdImmediate imageOperand = { true, *opIt++ };
4593 operands.push_back(imageOperand);
4594 }
4595#ifdef AMD_EXTENSIONS
4596 if (mask & spv::ImageOperandsLodMask) {
4597 spv::IdImmediate imageOperand = { true, *opIt++ };
4598 operands.push_back(imageOperand);
4599 }
4600#endif
4601 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004602 spv::IdImmediate imageOperand = { true,
4603 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004604 operands.push_back(imageOperand);
4605 }
4606
John Kessenich56bab042015-09-16 10:54:31 -06004607 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004608 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004609 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004610 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004611#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004612 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4613 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004614#else
Rex Xu5eafa472016-02-19 22:24:03 +08004615 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004616#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004617 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004618 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004619 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4620
Jeff Bolz36831c92018-09-05 10:11:41 -05004621 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004622 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004623 mask = mask | spv::ImageOperandsSampleMask;
4624 }
Rex Xu129799a2017-07-05 17:23:28 +08004625#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004626 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004627 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4628 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4629
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 mask = mask | spv::ImageOperandsLodMask;
4631 }
4632#endif
4633 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4634 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004635 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004636 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004637 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004638 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004639 }
4640 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004641 spv::IdImmediate imageOperand = { true, *opIt++ };
4642 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004643 }
4644#ifdef AMD_EXTENSIONS
4645 if (mask & spv::ImageOperandsLodMask) {
4646 spv::IdImmediate imageOperand = { true, *opIt++ };
4647 operands.push_back(imageOperand);
4648 }
Rex Xu129799a2017-07-05 17:23:28 +08004649#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004650 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4651 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4652 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004653 }
4654
4655 // Create the return type that was a special structure
4656 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004657 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004658 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4659 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4660
4661 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4662
4663 // Decode the return type
4664 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4665 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004666 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004667 // Process image atomic operations
4668
4669 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4670 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004671 // For non-MS, the sample value should be 0
4672 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4673 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004674
Jeff Bolz36831c92018-09-05 10:11:41 -05004675 spv::Id resultTypeId;
4676 // imageAtomicStore has a void return type so base the pointer type on
4677 // the type of the value operand.
4678 if (node->getOp() == glslang::EOpImageAtomicStore) {
4679 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4680 } else {
4681 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4682 }
John Kessenich56bab042015-09-16 10:54:31 -06004683 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004684
4685 std::vector<spv::Id> operands;
4686 operands.push_back(pointer);
4687 for (; opIt != arguments.end(); ++opIt)
4688 operands.push_back(*opIt);
4689
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004690 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004691 }
4692 }
4693
amhagan05506bb2017-06-13 16:53:02 -04004694#ifdef AMD_EXTENSIONS
4695 // Check for fragment mask functions other than queries
4696 if (cracked.fragMask) {
4697 assert(sampler.ms);
4698
4699 auto opIt = arguments.begin();
4700 std::vector<spv::Id> operands;
4701
4702 // Extract the image if necessary
4703 if (builder.isSampledImage(params.sampler))
4704 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4705
4706 operands.push_back(params.sampler);
4707 ++opIt;
4708
4709 if (sampler.isSubpass()) {
4710 // add on the (0,0) coordinate
4711 spv::Id zero = builder.makeIntConstant(0);
4712 std::vector<spv::Id> comps;
4713 comps.push_back(zero);
4714 comps.push_back(zero);
4715 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4716 }
4717
4718 for (; opIt != arguments.end(); ++opIt)
4719 operands.push_back(*opIt);
4720
4721 spv::Op fragMaskOp = spv::OpNop;
4722 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4723 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4724 else if (node->getOp() == glslang::EOpFragmentFetch)
4725 fragMaskOp = spv::OpFragmentFetchAMD;
4726
4727 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4728 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4729 return builder.createOp(fragMaskOp, resultType(), operands);
4730 }
4731#endif
4732
Rex Xufc618912015-09-09 16:42:49 +08004733 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004734 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004735#ifdef NV_EXTENSIONS
4736 bool imageFootprint = node->isImageFootprint();
4737#endif
4738
Rex Xu71519fe2015-11-11 15:35:47 +08004739 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4740
John Kessenichfc51d282015-08-19 13:34:18 -06004741 // check for bias argument
4742 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004743#ifdef AMD_EXTENSIONS
4744 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4745#else
Rex Xu71519fe2015-11-11 15:35:47 +08004746 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004747#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004748 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004749#ifdef AMD_EXTENSIONS
4750 if (cracked.gather)
4751 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004752
4753 if (f16ShadowCompare)
4754 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004755#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004756 if (cracked.offset)
4757 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004758#ifdef AMD_EXTENSIONS
4759 else if (cracked.offsets)
4760 ++nonBiasArgCount;
4761#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004762 if (cracked.grad)
4763 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004764 if (cracked.lodClamp)
4765 ++nonBiasArgCount;
4766 if (sparse)
4767 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004768#ifdef NV_EXTENSIONS
4769 if (imageFootprint)
4770 //Following three extra arguments
4771 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4772 nonBiasArgCount += 3;
4773#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004774 if ((int)arguments.size() > nonBiasArgCount)
4775 bias = true;
4776 }
4777
John Kessenicha5c33d62016-06-02 23:45:21 -06004778 // See if the sampler param should really be just the SPV image part
4779 if (cracked.fetch) {
4780 // a fetch needs to have the image extracted first
4781 if (builder.isSampledImage(params.sampler))
4782 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4783 }
4784
Rex Xu225e0fc2016-11-17 17:47:59 +08004785#ifdef AMD_EXTENSIONS
4786 if (cracked.gather) {
4787 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4788 if (bias || cracked.lod ||
4789 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4790 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004791 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004792 }
4793 }
4794#endif
4795
John Kessenichfc51d282015-08-19 13:34:18 -06004796 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004797
John Kessenichfc51d282015-08-19 13:34:18 -06004798 params.coords = arguments[1];
4799 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004800 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004801
4802 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004803#ifdef AMD_EXTENSIONS
4804 if (cubeCompare || f16ShadowCompare) {
4805#else
Rex Xu48edadf2015-12-31 16:11:41 +08004806 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004807#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004808 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004809 ++extraArgs;
4810 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004811 params.Dref = arguments[2];
4812 ++extraArgs;
4813 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004814 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004815 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004816 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004817 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004818 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004819 dRefComp = builder.getNumComponents(params.coords) - 1;
4820 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004821 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4822 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004823
4824 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004825 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004826 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004827 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004828 } else if (glslangIntermediate->getStage() != EShLangFragment
4829#ifdef NV_EXTENSIONS
4830 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4831 && !(glslangIntermediate->getStage() == EShLangCompute &&
4832 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4833#endif
4834 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004835 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4836 noImplicitLod = true;
4837 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004838
4839 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004840 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004841 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004842 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004843 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004844
4845 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004846 if (cracked.grad) {
4847 params.gradX = arguments[2 + extraArgs];
4848 params.gradY = arguments[3 + extraArgs];
4849 extraArgs += 2;
4850 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004851
4852 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004853 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004854 params.offset = arguments[2 + extraArgs];
4855 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004856 } else if (cracked.offsets) {
4857 params.offsets = arguments[2 + extraArgs];
4858 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004859 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004860
4861 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004862 if (cracked.lodClamp) {
4863 params.lodClamp = arguments[2 + extraArgs];
4864 ++extraArgs;
4865 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004866 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004867 if (sparse) {
4868 params.texelOut = arguments[2 + extraArgs];
4869 ++extraArgs;
4870 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004871
John Kessenich76d4dfc2016-06-16 12:43:23 -06004872 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004873 if (cracked.gather && ! sampler.shadow) {
4874 // default component is 0, if missing, otherwise an argument
4875 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004876 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004877 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004878 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004879 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004880 }
Chao Chen3a137962018-09-19 11:41:27 -07004881#ifdef NV_EXTENSIONS
4882 spv::Id resultStruct = spv::NoResult;
4883 if (imageFootprint) {
4884 //Following three extra arguments
4885 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4886 params.granularity = arguments[2 + extraArgs];
4887 params.coarse = arguments[3 + extraArgs];
4888 resultStruct = arguments[4 + extraArgs];
4889 extraArgs += 3;
4890 }
4891#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004892 // bias
4893 if (bias) {
4894 params.bias = arguments[2 + extraArgs];
4895 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004896 }
John Kessenichfc51d282015-08-19 13:34:18 -06004897
Chao Chen3a137962018-09-19 11:41:27 -07004898#ifdef NV_EXTENSIONS
4899 if (imageFootprint) {
4900 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4901 builder.addCapability(spv::CapabilityImageFootprintNV);
4902
4903
4904 //resultStructType(OpenGL type) contains 5 elements:
4905 //struct gl_TextureFootprint2DNV {
4906 // uvec2 anchor;
4907 // uvec2 offset;
4908 // uvec2 mask;
4909 // uint lod;
4910 // uint granularity;
4911 //};
4912 //or
4913 //struct gl_TextureFootprint3DNV {
4914 // uvec3 anchor;
4915 // uvec3 offset;
4916 // uvec2 mask;
4917 // uint lod;
4918 // uint granularity;
4919 //};
4920 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4921 assert(builder.isStructType(resultStructType));
4922
4923 //resType (SPIR-V type) contains 6 elements:
4924 //Member 0 must be a Boolean type scalar(LOD),
4925 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4926 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4927 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4928 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4929 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4930 std::vector<spv::Id> members;
4931 members.push_back(resultType());
4932 for (int i = 0; i < 5; i++) {
4933 members.push_back(builder.getContainedTypeId(resultStructType, i));
4934 }
4935 spv::Id resType = builder.makeStructType(members, "ResType");
4936
4937 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004938 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4939 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004940
4941 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4942 for (int i = 0; i < 5; i++) {
4943 builder.clearAccessChain();
4944 builder.setAccessChainLValue(resultStruct);
4945
4946 //Accessing to a struct we created, no coherent flag is set
4947 spv::Builder::AccessChain::CoherentFlags flags;
4948 flags.clear();
4949
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004950 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004951 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4952 }
4953 return builder.createCompositeExtract(res, resultType(), 0);
4954 }
4955#endif
4956
John Kessenich65336482016-06-16 14:06:26 -06004957 // projective component (might not to move)
4958 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4959 // are divided by the last component of P."
4960 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4961 // unused components will appear after all used components."
4962 if (cracked.proj) {
4963 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4964 int projTargetComp;
4965 switch (sampler.dim) {
4966 case glslang::Esd1D: projTargetComp = 1; break;
4967 case glslang::Esd2D: projTargetComp = 2; break;
4968 case glslang::EsdRect: projTargetComp = 2; break;
4969 default: projTargetComp = projSourceComp; break;
4970 }
4971 // copy the projective coordinate if we have to
4972 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004973 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004974 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4975 projSourceComp);
4976 params.coords = builder.createCompositeInsert(projComp, params.coords,
4977 builder.getTypeId(params.coords), projTargetComp);
4978 }
4979 }
4980
Jeff Bolz36831c92018-09-05 10:11:41 -05004981 // nonprivate
4982 if (imageType.getQualifier().nonprivate) {
4983 params.nonprivate = true;
4984 }
4985
4986 // volatile
4987 if (imageType.getQualifier().volatil) {
4988 params.volatil = true;
4989 }
4990
St0fFa1184dd2018-04-09 21:08:14 +02004991 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004992 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4993 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004994 );
LoopDawg4425f242018-02-18 11:40:01 -07004995
4996 if (components != node->getType().getVectorSize())
4997 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4998
4999 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005000}
5001
5002spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5003{
5004 // Grab the function's pointer from the previously created function
5005 spv::Function* function = functionMap[node->getName().c_str()];
5006 if (! function)
5007 return 0;
5008
5009 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5010 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5011
5012 // See comments in makeFunctions() for details about the semantics for parameter passing.
5013 //
5014 // These imply we need a four step process:
5015 // 1. Evaluate the arguments
5016 // 2. Allocate and make copies of in, out, and inout arguments
5017 // 3. Make the call
5018 // 4. Copy back the results
5019
John Kessenichd3ed90b2018-05-04 11:43:03 -06005020 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005021 std::vector<spv::Builder::AccessChain> lValues;
5022 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005023 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005024 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005025 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005026 // build l-value
5027 builder.clearAccessChain();
5028 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005029 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005030 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005031 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005032 // save l-value
5033 lValues.push_back(builder.getAccessChain());
5034 } else {
5035 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005036 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005037 }
5038 }
5039
5040 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5041 // copy the original into that space.
5042 //
5043 // Also, build up the list of actual arguments to pass in for the call
5044 int lValueCount = 0;
5045 int rValueCount = 0;
5046 std::vector<spv::Id> spvArgs;
5047 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5048 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005049 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005050 builder.setAccessChain(lValues[lValueCount]);
5051 arg = builder.accessChainGetLValue();
5052 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005053 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005054 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005055 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005056 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5057 // need to copy the input into output space
5058 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005059 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005060 builder.clearAccessChain();
5061 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005062 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005063 }
5064 ++lValueCount;
5065 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005066 // process r-value, which involves a copy for a type mismatch
5067 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5068 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5069 builder.clearAccessChain();
5070 builder.setAccessChainLValue(argCopy);
5071 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5072 arg = builder.createLoad(argCopy);
5073 } else
5074 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005075 ++rValueCount;
5076 }
5077 spvArgs.push_back(arg);
5078 }
5079
5080 // 3. Make the call.
5081 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005082 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005083
5084 // 4. Copy back out an "out" arguments.
5085 lValueCount = 0;
5086 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005087 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005088 ++lValueCount;
5089 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005090 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5091 spv::Id copy = builder.createLoad(spvArgs[a]);
5092 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005093 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005094 }
5095 ++lValueCount;
5096 }
5097 }
5098
5099 return result;
5100}
5101
5102// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005103spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005104 spv::Id typeId, spv::Id left, spv::Id right,
5105 glslang::TBasicType typeProxy, bool reduceComparison)
5106{
John Kessenich66011cb2018-03-06 16:12:04 -07005107 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5108 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005109 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005110
5111 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005112 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005113 bool comparison = false;
5114
5115 switch (op) {
5116 case glslang::EOpAdd:
5117 case glslang::EOpAddAssign:
5118 if (isFloat)
5119 binOp = spv::OpFAdd;
5120 else
5121 binOp = spv::OpIAdd;
5122 break;
5123 case glslang::EOpSub:
5124 case glslang::EOpSubAssign:
5125 if (isFloat)
5126 binOp = spv::OpFSub;
5127 else
5128 binOp = spv::OpISub;
5129 break;
5130 case glslang::EOpMul:
5131 case glslang::EOpMulAssign:
5132 if (isFloat)
5133 binOp = spv::OpFMul;
5134 else
5135 binOp = spv::OpIMul;
5136 break;
5137 case glslang::EOpVectorTimesScalar:
5138 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005139 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005140 if (builder.isVector(right))
5141 std::swap(left, right);
5142 assert(builder.isScalar(right));
5143 needMatchingVectors = false;
5144 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005145 } else if (isFloat)
5146 binOp = spv::OpFMul;
5147 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005148 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005149 break;
5150 case glslang::EOpVectorTimesMatrix:
5151 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005152 binOp = spv::OpVectorTimesMatrix;
5153 break;
5154 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005155 binOp = spv::OpMatrixTimesVector;
5156 break;
5157 case glslang::EOpMatrixTimesScalar:
5158 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005159 binOp = spv::OpMatrixTimesScalar;
5160 break;
5161 case glslang::EOpMatrixTimesMatrix:
5162 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005163 binOp = spv::OpMatrixTimesMatrix;
5164 break;
5165 case glslang::EOpOuterProduct:
5166 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005167 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005168 break;
5169
5170 case glslang::EOpDiv:
5171 case glslang::EOpDivAssign:
5172 if (isFloat)
5173 binOp = spv::OpFDiv;
5174 else if (isUnsigned)
5175 binOp = spv::OpUDiv;
5176 else
5177 binOp = spv::OpSDiv;
5178 break;
5179 case glslang::EOpMod:
5180 case glslang::EOpModAssign:
5181 if (isFloat)
5182 binOp = spv::OpFMod;
5183 else if (isUnsigned)
5184 binOp = spv::OpUMod;
5185 else
5186 binOp = spv::OpSMod;
5187 break;
5188 case glslang::EOpRightShift:
5189 case glslang::EOpRightShiftAssign:
5190 if (isUnsigned)
5191 binOp = spv::OpShiftRightLogical;
5192 else
5193 binOp = spv::OpShiftRightArithmetic;
5194 break;
5195 case glslang::EOpLeftShift:
5196 case glslang::EOpLeftShiftAssign:
5197 binOp = spv::OpShiftLeftLogical;
5198 break;
5199 case glslang::EOpAnd:
5200 case glslang::EOpAndAssign:
5201 binOp = spv::OpBitwiseAnd;
5202 break;
5203 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005204 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005205 binOp = spv::OpLogicalAnd;
5206 break;
5207 case glslang::EOpInclusiveOr:
5208 case glslang::EOpInclusiveOrAssign:
5209 binOp = spv::OpBitwiseOr;
5210 break;
5211 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005212 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 binOp = spv::OpLogicalOr;
5214 break;
5215 case glslang::EOpExclusiveOr:
5216 case glslang::EOpExclusiveOrAssign:
5217 binOp = spv::OpBitwiseXor;
5218 break;
5219 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005220 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223
5224 case glslang::EOpLessThan:
5225 case glslang::EOpGreaterThan:
5226 case glslang::EOpLessThanEqual:
5227 case glslang::EOpGreaterThanEqual:
5228 case glslang::EOpEqual:
5229 case glslang::EOpNotEqual:
5230 case glslang::EOpVectorEqual:
5231 case glslang::EOpVectorNotEqual:
5232 comparison = true;
5233 break;
5234 default:
5235 break;
5236 }
5237
John Kessenich7c1aa102015-10-15 13:29:11 -06005238 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005239 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005240 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005241 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5242 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005243 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005244
5245 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005246 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005247 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005248
qining25262b32016-05-06 17:25:16 -04005249 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005250 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005251 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005252 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005253 }
5254
5255 if (! comparison)
5256 return 0;
5257
John Kessenich7c1aa102015-10-15 13:29:11 -06005258 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005259
John Kessenich4583b612016-08-07 19:14:22 -06005260 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005261 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5262 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005263 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005264 return result;
5265 }
John Kessenich140f3df2015-06-26 16:58:36 -06005266
5267 switch (op) {
5268 case glslang::EOpLessThan:
5269 if (isFloat)
5270 binOp = spv::OpFOrdLessThan;
5271 else if (isUnsigned)
5272 binOp = spv::OpULessThan;
5273 else
5274 binOp = spv::OpSLessThan;
5275 break;
5276 case glslang::EOpGreaterThan:
5277 if (isFloat)
5278 binOp = spv::OpFOrdGreaterThan;
5279 else if (isUnsigned)
5280 binOp = spv::OpUGreaterThan;
5281 else
5282 binOp = spv::OpSGreaterThan;
5283 break;
5284 case glslang::EOpLessThanEqual:
5285 if (isFloat)
5286 binOp = spv::OpFOrdLessThanEqual;
5287 else if (isUnsigned)
5288 binOp = spv::OpULessThanEqual;
5289 else
5290 binOp = spv::OpSLessThanEqual;
5291 break;
5292 case glslang::EOpGreaterThanEqual:
5293 if (isFloat)
5294 binOp = spv::OpFOrdGreaterThanEqual;
5295 else if (isUnsigned)
5296 binOp = spv::OpUGreaterThanEqual;
5297 else
5298 binOp = spv::OpSGreaterThanEqual;
5299 break;
5300 case glslang::EOpEqual:
5301 case glslang::EOpVectorEqual:
5302 if (isFloat)
5303 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005304 else if (isBool)
5305 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005306 else
5307 binOp = spv::OpIEqual;
5308 break;
5309 case glslang::EOpNotEqual:
5310 case glslang::EOpVectorNotEqual:
5311 if (isFloat)
5312 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005313 else if (isBool)
5314 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 else
5316 binOp = spv::OpINotEqual;
5317 break;
5318 default:
5319 break;
5320 }
5321
qining25262b32016-05-06 17:25:16 -04005322 if (binOp != spv::OpNop) {
5323 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005324 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005325 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005326 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005327 }
John Kessenich140f3df2015-06-26 16:58:36 -06005328
5329 return 0;
5330}
5331
John Kessenich04bb8a02015-12-12 12:28:14 -07005332//
5333// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5334// These can be any of:
5335//
5336// matrix * scalar
5337// scalar * matrix
5338// matrix * matrix linear algebraic
5339// matrix * vector
5340// vector * matrix
5341// matrix * matrix componentwise
5342// matrix op matrix op in {+, -, /}
5343// matrix op scalar op in {+, -, /}
5344// scalar op matrix op in {+, -, /}
5345//
John Kessenichead86222018-03-28 18:01:20 -06005346spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5347 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005348{
5349 bool firstClass = true;
5350
5351 // First, handle first-class matrix operations (* and matrix/scalar)
5352 switch (op) {
5353 case spv::OpFDiv:
5354 if (builder.isMatrix(left) && builder.isScalar(right)) {
5355 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005356 spv::Id resultType = builder.getTypeId(right);
5357 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005358 op = spv::OpMatrixTimesScalar;
5359 } else
5360 firstClass = false;
5361 break;
5362 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005363 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005364 std::swap(left, right);
5365 assert(builder.isScalar(right));
5366 break;
5367 case spv::OpVectorTimesMatrix:
5368 assert(builder.isVector(left));
5369 assert(builder.isMatrix(right));
5370 break;
5371 case spv::OpMatrixTimesVector:
5372 assert(builder.isMatrix(left));
5373 assert(builder.isVector(right));
5374 break;
5375 case spv::OpMatrixTimesMatrix:
5376 assert(builder.isMatrix(left));
5377 assert(builder.isMatrix(right));
5378 break;
5379 default:
5380 firstClass = false;
5381 break;
5382 }
5383
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005384 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5385 firstClass = true;
5386
qining25262b32016-05-06 17:25:16 -04005387 if (firstClass) {
5388 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005389 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005390 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005391 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005392 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005393
LoopDawg592860c2016-06-09 08:57:35 -06005394 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005395 // The result type of all of them is the same type as the (a) matrix operand.
5396 // The algorithm is to:
5397 // - break the matrix(es) into vectors
5398 // - smear any scalar to a vector
5399 // - do vector operations
5400 // - make a matrix out the vector results
5401 switch (op) {
5402 case spv::OpFAdd:
5403 case spv::OpFSub:
5404 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005405 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005406 case spv::OpFMul:
5407 {
5408 // one time set up...
5409 bool leftMat = builder.isMatrix(left);
5410 bool rightMat = builder.isMatrix(right);
5411 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5412 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5413 spv::Id scalarType = builder.getScalarTypeId(typeId);
5414 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5415 std::vector<spv::Id> results;
5416 spv::Id smearVec = spv::NoResult;
5417 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005418 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005419 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005420 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005421
5422 // do each vector op
5423 for (unsigned int c = 0; c < numCols; ++c) {
5424 std::vector<unsigned int> indexes;
5425 indexes.push_back(c);
5426 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5427 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005428 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005429 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005430 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005431 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005432 }
5433
5434 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005435 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005436 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005437 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005438 }
5439 default:
5440 assert(0);
5441 return spv::NoResult;
5442 }
5443}
5444
John Kessenichead86222018-03-28 18:01:20 -06005445spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005446 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005447{
5448 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005449 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005451 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5452 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005453
5454 switch (op) {
5455 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005456 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005457 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005458 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005459 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005460 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005461 unaryOp = spv::OpSNegate;
5462 break;
5463
5464 case glslang::EOpLogicalNot:
5465 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 unaryOp = spv::OpLogicalNot;
5467 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 case glslang::EOpBitwiseNot:
5469 unaryOp = spv::OpNot;
5470 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005471
John Kessenich140f3df2015-06-26 16:58:36 -06005472 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005473 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
5478 case glslang::EOpTranspose:
5479 unaryOp = spv::OpTranspose;
5480 break;
5481
5482 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005498 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005501 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005502 break;
5503 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506
5507 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005508 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005509 break;
5510 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005511 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005512 break;
5513 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005514 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005515 break;
5516 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005517 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005518 break;
5519 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005520 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005521 break;
5522 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005523 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 break;
5525
5526 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005527 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005528 break;
5529 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005530 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 break;
5532
5533 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005543 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005544 break;
5545 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005546 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005547 break;
5548 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005549 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005550 break;
5551
5552 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 break;
5555 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005556 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005557 break;
5558 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005559 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005560 break;
5561 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005562 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005563 break;
5564 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005565 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005566 break;
5567 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005568 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005569 break;
5570
5571 case glslang::EOpIsNan:
5572 unaryOp = spv::OpIsNan;
5573 break;
5574 case glslang::EOpIsInf:
5575 unaryOp = spv::OpIsInf;
5576 break;
LoopDawg592860c2016-06-09 08:57:35 -06005577 case glslang::EOpIsFinite:
5578 unaryOp = spv::OpIsFinite;
5579 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005580
Rex Xucbc426e2015-12-15 16:03:10 +08005581 case glslang::EOpFloatBitsToInt:
5582 case glslang::EOpFloatBitsToUint:
5583 case glslang::EOpIntBitsToFloat:
5584 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005585 case glslang::EOpDoubleBitsToInt64:
5586 case glslang::EOpDoubleBitsToUint64:
5587 case glslang::EOpInt64BitsToDouble:
5588 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005589 case glslang::EOpFloat16BitsToInt16:
5590 case glslang::EOpFloat16BitsToUint16:
5591 case glslang::EOpInt16BitsToFloat16:
5592 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005593 unaryOp = spv::OpBitcast;
5594 break;
5595
John Kessenich140f3df2015-06-26 16:58:36 -06005596 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005597 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005598 break;
5599 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005600 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005601 break;
5602 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005603 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005604 break;
5605 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005606 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005607 break;
5608 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005609 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005610 break;
5611 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005612 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005613 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005614 case glslang::EOpPackSnorm4x8:
5615 libCall = spv::GLSLstd450PackSnorm4x8;
5616 break;
5617 case glslang::EOpUnpackSnorm4x8:
5618 libCall = spv::GLSLstd450UnpackSnorm4x8;
5619 break;
5620 case glslang::EOpPackUnorm4x8:
5621 libCall = spv::GLSLstd450PackUnorm4x8;
5622 break;
5623 case glslang::EOpUnpackUnorm4x8:
5624 libCall = spv::GLSLstd450UnpackUnorm4x8;
5625 break;
5626 case glslang::EOpPackDouble2x32:
5627 libCall = spv::GLSLstd450PackDouble2x32;
5628 break;
5629 case glslang::EOpUnpackDouble2x32:
5630 libCall = spv::GLSLstd450UnpackDouble2x32;
5631 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005632
Rex Xu8ff43de2016-04-22 16:51:45 +08005633 case glslang::EOpPackInt2x32:
5634 case glslang::EOpUnpackInt2x32:
5635 case glslang::EOpPackUint2x32:
5636 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005637 case glslang::EOpPack16:
5638 case glslang::EOpPack32:
5639 case glslang::EOpPack64:
5640 case glslang::EOpUnpack32:
5641 case glslang::EOpUnpack16:
5642 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005643 case glslang::EOpPackInt2x16:
5644 case glslang::EOpUnpackInt2x16:
5645 case glslang::EOpPackUint2x16:
5646 case glslang::EOpUnpackUint2x16:
5647 case glslang::EOpPackInt4x16:
5648 case glslang::EOpUnpackInt4x16:
5649 case glslang::EOpPackUint4x16:
5650 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005651 case glslang::EOpPackFloat2x16:
5652 case glslang::EOpUnpackFloat2x16:
5653 unaryOp = spv::OpBitcast;
5654 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005655
John Kessenich140f3df2015-06-26 16:58:36 -06005656 case glslang::EOpDPdx:
5657 unaryOp = spv::OpDPdx;
5658 break;
5659 case glslang::EOpDPdy:
5660 unaryOp = spv::OpDPdy;
5661 break;
5662 case glslang::EOpFwidth:
5663 unaryOp = spv::OpFwidth;
5664 break;
5665 case glslang::EOpDPdxFine:
5666 unaryOp = spv::OpDPdxFine;
5667 break;
5668 case glslang::EOpDPdyFine:
5669 unaryOp = spv::OpDPdyFine;
5670 break;
5671 case glslang::EOpFwidthFine:
5672 unaryOp = spv::OpFwidthFine;
5673 break;
5674 case glslang::EOpDPdxCoarse:
5675 unaryOp = spv::OpDPdxCoarse;
5676 break;
5677 case glslang::EOpDPdyCoarse:
5678 unaryOp = spv::OpDPdyCoarse;
5679 break;
5680 case glslang::EOpFwidthCoarse:
5681 unaryOp = spv::OpFwidthCoarse;
5682 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005683 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005684#ifdef AMD_EXTENSIONS
5685 if (typeProxy == glslang::EbtFloat16)
5686 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5687#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005688 libCall = spv::GLSLstd450InterpolateAtCentroid;
5689 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005690 case glslang::EOpAny:
5691 unaryOp = spv::OpAny;
5692 break;
5693 case glslang::EOpAll:
5694 unaryOp = spv::OpAll;
5695 break;
5696
5697 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005698 if (isFloat)
5699 libCall = spv::GLSLstd450FAbs;
5700 else
5701 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005702 break;
5703 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005704 if (isFloat)
5705 libCall = spv::GLSLstd450FSign;
5706 else
5707 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005708 break;
5709
John Kessenichfc51d282015-08-19 13:34:18 -06005710 case glslang::EOpAtomicCounterIncrement:
5711 case glslang::EOpAtomicCounterDecrement:
5712 case glslang::EOpAtomicCounter:
5713 {
5714 // Handle all of the atomics in one place, in createAtomicOperation()
5715 std::vector<spv::Id> operands;
5716 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005717 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005718 }
5719
John Kessenichfc51d282015-08-19 13:34:18 -06005720 case glslang::EOpBitFieldReverse:
5721 unaryOp = spv::OpBitReverse;
5722 break;
5723 case glslang::EOpBitCount:
5724 unaryOp = spv::OpBitCount;
5725 break;
5726 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005727 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005728 break;
5729 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005730 if (isUnsigned)
5731 libCall = spv::GLSLstd450FindUMsb;
5732 else
5733 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005734 break;
5735
Rex Xu574ab042016-04-14 16:53:07 +08005736 case glslang::EOpBallot:
5737 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005738 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005739 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005740 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005741#ifdef AMD_EXTENSIONS
5742 case glslang::EOpMinInvocations:
5743 case glslang::EOpMaxInvocations:
5744 case glslang::EOpAddInvocations:
5745 case glslang::EOpMinInvocationsNonUniform:
5746 case glslang::EOpMaxInvocationsNonUniform:
5747 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005748 case glslang::EOpMinInvocationsInclusiveScan:
5749 case glslang::EOpMaxInvocationsInclusiveScan:
5750 case glslang::EOpAddInvocationsInclusiveScan:
5751 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5752 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5753 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5754 case glslang::EOpMinInvocationsExclusiveScan:
5755 case glslang::EOpMaxInvocationsExclusiveScan:
5756 case glslang::EOpAddInvocationsExclusiveScan:
5757 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5758 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5759 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005760#endif
Rex Xu51596642016-09-21 18:56:12 +08005761 {
5762 std::vector<spv::Id> operands;
5763 operands.push_back(operand);
5764 return createInvocationsOperation(op, typeId, operands, typeProxy);
5765 }
John Kessenich66011cb2018-03-06 16:12:04 -07005766 case glslang::EOpSubgroupAll:
5767 case glslang::EOpSubgroupAny:
5768 case glslang::EOpSubgroupAllEqual:
5769 case glslang::EOpSubgroupBroadcastFirst:
5770 case glslang::EOpSubgroupBallot:
5771 case glslang::EOpSubgroupInverseBallot:
5772 case glslang::EOpSubgroupBallotBitCount:
5773 case glslang::EOpSubgroupBallotInclusiveBitCount:
5774 case glslang::EOpSubgroupBallotExclusiveBitCount:
5775 case glslang::EOpSubgroupBallotFindLSB:
5776 case glslang::EOpSubgroupBallotFindMSB:
5777 case glslang::EOpSubgroupAdd:
5778 case glslang::EOpSubgroupMul:
5779 case glslang::EOpSubgroupMin:
5780 case glslang::EOpSubgroupMax:
5781 case glslang::EOpSubgroupAnd:
5782 case glslang::EOpSubgroupOr:
5783 case glslang::EOpSubgroupXor:
5784 case glslang::EOpSubgroupInclusiveAdd:
5785 case glslang::EOpSubgroupInclusiveMul:
5786 case glslang::EOpSubgroupInclusiveMin:
5787 case glslang::EOpSubgroupInclusiveMax:
5788 case glslang::EOpSubgroupInclusiveAnd:
5789 case glslang::EOpSubgroupInclusiveOr:
5790 case glslang::EOpSubgroupInclusiveXor:
5791 case glslang::EOpSubgroupExclusiveAdd:
5792 case glslang::EOpSubgroupExclusiveMul:
5793 case glslang::EOpSubgroupExclusiveMin:
5794 case glslang::EOpSubgroupExclusiveMax:
5795 case glslang::EOpSubgroupExclusiveAnd:
5796 case glslang::EOpSubgroupExclusiveOr:
5797 case glslang::EOpSubgroupExclusiveXor:
5798 case glslang::EOpSubgroupQuadSwapHorizontal:
5799 case glslang::EOpSubgroupQuadSwapVertical:
5800 case glslang::EOpSubgroupQuadSwapDiagonal: {
5801 std::vector<spv::Id> operands;
5802 operands.push_back(operand);
5803 return createSubgroupOperation(op, typeId, operands, typeProxy);
5804 }
Rex Xu9d93a232016-05-05 12:30:44 +08005805#ifdef AMD_EXTENSIONS
5806 case glslang::EOpMbcnt:
5807 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5808 libCall = spv::MbcntAMD;
5809 break;
5810
5811 case glslang::EOpCubeFaceIndex:
5812 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5813 libCall = spv::CubeFaceIndexAMD;
5814 break;
5815
5816 case glslang::EOpCubeFaceCoord:
5817 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5818 libCall = spv::CubeFaceCoordAMD;
5819 break;
5820#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005821#ifdef NV_EXTENSIONS
5822 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005823 unaryOp = spv::OpGroupNonUniformPartitionNV;
5824 break;
5825#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005826 case glslang::EOpConstructReference:
5827 unaryOp = spv::OpBitcast;
5828 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005829
5830 case glslang::EOpCopyObject:
5831 unaryOp = spv::OpCopyObject;
5832 break;
5833
John Kessenich140f3df2015-06-26 16:58:36 -06005834 default:
5835 return 0;
5836 }
5837
5838 spv::Id id;
5839 if (libCall >= 0) {
5840 std::vector<spv::Id> args;
5841 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005842 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005843 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005844 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005845 }
John Kessenich140f3df2015-06-26 16:58:36 -06005846
John Kessenichead86222018-03-28 18:01:20 -06005847 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005848 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005849 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005850}
5851
John Kessenich7a53f762016-01-20 11:19:27 -07005852// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005853spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5854 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005855{
5856 // Handle unary operations vector by vector.
5857 // The result type is the same type as the original type.
5858 // The algorithm is to:
5859 // - break the matrix into vectors
5860 // - apply the operation to each vector
5861 // - make a matrix out the vector results
5862
5863 // get the types sorted out
5864 int numCols = builder.getNumColumns(operand);
5865 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005866 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5867 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005868 std::vector<spv::Id> results;
5869
5870 // do each vector op
5871 for (int c = 0; c < numCols; ++c) {
5872 std::vector<unsigned int> indexes;
5873 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005874 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5875 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005876 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005877 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005878 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005879 }
5880
5881 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005882 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005883 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005884 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005885}
5886
John Kessenichad7645f2018-06-04 19:11:25 -06005887// For converting integers where both the bitwidth and the signedness could
5888// change, but only do the width change here. The caller is still responsible
5889// for the signedness conversion.
5890spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005891{
John Kessenichad7645f2018-06-04 19:11:25 -06005892 // Get the result type width, based on the type to convert to.
5893 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005894 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005895 case glslang::EOpConvInt16ToUint8:
5896 case glslang::EOpConvIntToUint8:
5897 case glslang::EOpConvInt64ToUint8:
5898 case glslang::EOpConvUint16ToInt8:
5899 case glslang::EOpConvUintToInt8:
5900 case glslang::EOpConvUint64ToInt8:
5901 width = 8;
5902 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005903 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005904 case glslang::EOpConvIntToUint16:
5905 case glslang::EOpConvInt64ToUint16:
5906 case glslang::EOpConvUint8ToInt16:
5907 case glslang::EOpConvUintToInt16:
5908 case glslang::EOpConvUint64ToInt16:
5909 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005910 break;
5911 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005912 case glslang::EOpConvInt16ToUint:
5913 case glslang::EOpConvInt64ToUint:
5914 case glslang::EOpConvUint8ToInt:
5915 case glslang::EOpConvUint16ToInt:
5916 case glslang::EOpConvUint64ToInt:
5917 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005918 break;
5919 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005920 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005921 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005922 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005923 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005924 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005925 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005926 break;
5927
5928 default:
5929 assert(false && "Default missing");
5930 break;
5931 }
5932
John Kessenichad7645f2018-06-04 19:11:25 -06005933 // Get the conversion operation and result type,
5934 // based on the target width, but the source type.
5935 spv::Id type = spv::NoType;
5936 spv::Op convOp = spv::OpNop;
5937 switch(op) {
5938 case glslang::EOpConvInt8ToUint16:
5939 case glslang::EOpConvInt8ToUint:
5940 case glslang::EOpConvInt8ToUint64:
5941 case glslang::EOpConvInt16ToUint8:
5942 case glslang::EOpConvInt16ToUint:
5943 case glslang::EOpConvInt16ToUint64:
5944 case glslang::EOpConvIntToUint8:
5945 case glslang::EOpConvIntToUint16:
5946 case glslang::EOpConvIntToUint64:
5947 case glslang::EOpConvInt64ToUint8:
5948 case glslang::EOpConvInt64ToUint16:
5949 case glslang::EOpConvInt64ToUint:
5950 convOp = spv::OpSConvert;
5951 type = builder.makeIntType(width);
5952 break;
5953 default:
5954 convOp = spv::OpUConvert;
5955 type = builder.makeUintType(width);
5956 break;
5957 }
5958
John Kessenich66011cb2018-03-06 16:12:04 -07005959 if (vectorSize > 0)
5960 type = builder.makeVectorType(type, vectorSize);
5961
John Kessenichad7645f2018-06-04 19:11:25 -06005962 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005963}
5964
John Kessenichead86222018-03-28 18:01:20 -06005965spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5966 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005967{
5968 spv::Op convOp = spv::OpNop;
5969 spv::Id zero = 0;
5970 spv::Id one = 0;
5971
5972 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5973
5974 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005975 case glslang::EOpConvInt8ToBool:
5976 case glslang::EOpConvUint8ToBool:
5977 zero = builder.makeUint8Constant(0);
5978 zero = makeSmearedConstant(zero, vectorSize);
5979 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005980 case glslang::EOpConvInt16ToBool:
5981 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005982 zero = builder.makeUint16Constant(0);
5983 zero = makeSmearedConstant(zero, vectorSize);
5984 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5985 case glslang::EOpConvIntToBool:
5986 case glslang::EOpConvUintToBool:
5987 zero = builder.makeUintConstant(0);
5988 zero = makeSmearedConstant(zero, vectorSize);
5989 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5990 case glslang::EOpConvInt64ToBool:
5991 case glslang::EOpConvUint64ToBool:
5992 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005993 zero = makeSmearedConstant(zero, vectorSize);
5994 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5995
5996 case glslang::EOpConvFloatToBool:
5997 zero = builder.makeFloatConstant(0.0F);
5998 zero = makeSmearedConstant(zero, vectorSize);
5999 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6000
6001 case glslang::EOpConvDoubleToBool:
6002 zero = builder.makeDoubleConstant(0.0);
6003 zero = makeSmearedConstant(zero, vectorSize);
6004 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6005
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006006 case glslang::EOpConvFloat16ToBool:
6007 zero = builder.makeFloat16Constant(0.0F);
6008 zero = makeSmearedConstant(zero, vectorSize);
6009 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006010
John Kessenich140f3df2015-06-26 16:58:36 -06006011 case glslang::EOpConvBoolToFloat:
6012 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006013 zero = builder.makeFloatConstant(0.0F);
6014 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006016
John Kessenich140f3df2015-06-26 16:58:36 -06006017 case glslang::EOpConvBoolToDouble:
6018 convOp = spv::OpSelect;
6019 zero = builder.makeDoubleConstant(0.0);
6020 one = builder.makeDoubleConstant(1.0);
6021 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006022
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006023 case glslang::EOpConvBoolToFloat16:
6024 convOp = spv::OpSelect;
6025 zero = builder.makeFloat16Constant(0.0F);
6026 one = builder.makeFloat16Constant(1.0F);
6027 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006028
6029 case glslang::EOpConvBoolToInt8:
6030 zero = builder.makeInt8Constant(0);
6031 one = builder.makeInt8Constant(1);
6032 convOp = spv::OpSelect;
6033 break;
6034
6035 case glslang::EOpConvBoolToUint8:
6036 zero = builder.makeUint8Constant(0);
6037 one = builder.makeUint8Constant(1);
6038 convOp = spv::OpSelect;
6039 break;
6040
6041 case glslang::EOpConvBoolToInt16:
6042 zero = builder.makeInt16Constant(0);
6043 one = builder.makeInt16Constant(1);
6044 convOp = spv::OpSelect;
6045 break;
6046
6047 case glslang::EOpConvBoolToUint16:
6048 zero = builder.makeUint16Constant(0);
6049 one = builder.makeUint16Constant(1);
6050 convOp = spv::OpSelect;
6051 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006052
John Kessenich140f3df2015-06-26 16:58:36 -06006053 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006054 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006055 if (op == glslang::EOpConvBoolToInt64)
6056 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006057 else
6058 zero = builder.makeIntConstant(0);
6059
6060 if (op == glslang::EOpConvBoolToInt64)
6061 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006062 else
6063 one = builder.makeIntConstant(1);
6064
John Kessenich140f3df2015-06-26 16:58:36 -06006065 convOp = spv::OpSelect;
6066 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006067
John Kessenich140f3df2015-06-26 16:58:36 -06006068 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006069 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08006070 if (op == glslang::EOpConvBoolToUint64)
6071 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006072 else
6073 zero = builder.makeUintConstant(0);
6074
6075 if (op == glslang::EOpConvBoolToUint64)
6076 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006077 else
6078 one = builder.makeUintConstant(1);
6079
John Kessenich140f3df2015-06-26 16:58:36 -06006080 convOp = spv::OpSelect;
6081 break;
6082
John Kessenich66011cb2018-03-06 16:12:04 -07006083 case glslang::EOpConvInt8ToFloat16:
6084 case glslang::EOpConvInt8ToFloat:
6085 case glslang::EOpConvInt8ToDouble:
6086 case glslang::EOpConvInt16ToFloat16:
6087 case glslang::EOpConvInt16ToFloat:
6088 case glslang::EOpConvInt16ToDouble:
6089 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006090 case glslang::EOpConvIntToFloat:
6091 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006092 case glslang::EOpConvInt64ToFloat:
6093 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006094 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006095 convOp = spv::OpConvertSToF;
6096 break;
6097
John Kessenich66011cb2018-03-06 16:12:04 -07006098 case glslang::EOpConvUint8ToFloat16:
6099 case glslang::EOpConvUint8ToFloat:
6100 case glslang::EOpConvUint8ToDouble:
6101 case glslang::EOpConvUint16ToFloat16:
6102 case glslang::EOpConvUint16ToFloat:
6103 case glslang::EOpConvUint16ToDouble:
6104 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006105 case glslang::EOpConvUintToFloat:
6106 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006107 case glslang::EOpConvUint64ToFloat:
6108 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006109 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006110 convOp = spv::OpConvertUToF;
6111 break;
6112
6113 case glslang::EOpConvDoubleToFloat:
6114 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006115 case glslang::EOpConvDoubleToFloat16:
6116 case glslang::EOpConvFloat16ToDouble:
6117 case glslang::EOpConvFloatToFloat16:
6118 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006119 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006120 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006121 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006122 break;
6123
John Kessenich66011cb2018-03-06 16:12:04 -07006124 case glslang::EOpConvFloat16ToInt8:
6125 case glslang::EOpConvFloatToInt8:
6126 case glslang::EOpConvDoubleToInt8:
6127 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006128 case glslang::EOpConvFloatToInt16:
6129 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006130 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006131 case glslang::EOpConvFloatToInt:
6132 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006133 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006134 case glslang::EOpConvFloatToInt64:
6135 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006136 convOp = spv::OpConvertFToS;
6137 break;
6138
John Kessenich66011cb2018-03-06 16:12:04 -07006139 case glslang::EOpConvUint8ToInt8:
6140 case glslang::EOpConvInt8ToUint8:
6141 case glslang::EOpConvUint16ToInt16:
6142 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006143 case glslang::EOpConvUintToInt:
6144 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006145 case glslang::EOpConvUint64ToInt64:
6146 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006147 if (builder.isInSpecConstCodeGenMode()) {
6148 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006149 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6150 zero = builder.makeUint8Constant(0);
6151 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006152 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006153 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6154 zero = builder.makeUint64Constant(0);
6155 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006156 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006157 }
qining189b2032016-04-12 23:16:20 -04006158 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006159 // Use OpIAdd, instead of OpBitcast to do the conversion when
6160 // generating for OpSpecConstantOp instruction.
6161 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6162 }
6163 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006164 convOp = spv::OpBitcast;
6165 break;
6166
John Kessenich66011cb2018-03-06 16:12:04 -07006167 case glslang::EOpConvFloat16ToUint8:
6168 case glslang::EOpConvFloatToUint8:
6169 case glslang::EOpConvDoubleToUint8:
6170 case glslang::EOpConvFloat16ToUint16:
6171 case glslang::EOpConvFloatToUint16:
6172 case glslang::EOpConvDoubleToUint16:
6173 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006174 case glslang::EOpConvFloatToUint:
6175 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006176 case glslang::EOpConvFloatToUint64:
6177 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006178 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006179 convOp = spv::OpConvertFToU;
6180 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006181
John Kessenich66011cb2018-03-06 16:12:04 -07006182 case glslang::EOpConvInt8ToInt16:
6183 case glslang::EOpConvInt8ToInt:
6184 case glslang::EOpConvInt8ToInt64:
6185 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006186 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006187 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006188 case glslang::EOpConvIntToInt8:
6189 case glslang::EOpConvIntToInt16:
6190 case glslang::EOpConvIntToInt64:
6191 case glslang::EOpConvInt64ToInt8:
6192 case glslang::EOpConvInt64ToInt16:
6193 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006194 convOp = spv::OpSConvert;
6195 break;
6196
John Kessenich66011cb2018-03-06 16:12:04 -07006197 case glslang::EOpConvUint8ToUint16:
6198 case glslang::EOpConvUint8ToUint:
6199 case glslang::EOpConvUint8ToUint64:
6200 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006201 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006202 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006203 case glslang::EOpConvUintToUint8:
6204 case glslang::EOpConvUintToUint16:
6205 case glslang::EOpConvUintToUint64:
6206 case glslang::EOpConvUint64ToUint8:
6207 case glslang::EOpConvUint64ToUint16:
6208 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006209 convOp = spv::OpUConvert;
6210 break;
6211
John Kessenich66011cb2018-03-06 16:12:04 -07006212 case glslang::EOpConvInt8ToUint16:
6213 case glslang::EOpConvInt8ToUint:
6214 case glslang::EOpConvInt8ToUint64:
6215 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006216 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006217 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006218 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006219 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006220 case glslang::EOpConvIntToUint64:
6221 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006222 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006223 case glslang::EOpConvInt64ToUint:
6224 case glslang::EOpConvUint8ToInt16:
6225 case glslang::EOpConvUint8ToInt:
6226 case glslang::EOpConvUint8ToInt64:
6227 case glslang::EOpConvUint16ToInt8:
6228 case glslang::EOpConvUint16ToInt:
6229 case glslang::EOpConvUint16ToInt64:
6230 case glslang::EOpConvUintToInt8:
6231 case glslang::EOpConvUintToInt16:
6232 case glslang::EOpConvUintToInt64:
6233 case glslang::EOpConvUint64ToInt8:
6234 case glslang::EOpConvUint64ToInt16:
6235 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006236 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006237 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006238
6239 if (builder.isInSpecConstCodeGenMode()) {
6240 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006241 switch(op) {
6242 case glslang::EOpConvInt16ToUint8:
6243 case glslang::EOpConvIntToUint8:
6244 case glslang::EOpConvInt64ToUint8:
6245 case glslang::EOpConvUint16ToInt8:
6246 case glslang::EOpConvUintToInt8:
6247 case glslang::EOpConvUint64ToInt8:
6248 zero = builder.makeUint8Constant(0);
6249 break;
6250 case glslang::EOpConvInt8ToUint16:
6251 case glslang::EOpConvIntToUint16:
6252 case glslang::EOpConvInt64ToUint16:
6253 case glslang::EOpConvUint8ToInt16:
6254 case glslang::EOpConvUintToInt16:
6255 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006256 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006257 break;
6258 case glslang::EOpConvInt8ToUint:
6259 case glslang::EOpConvInt16ToUint:
6260 case glslang::EOpConvInt64ToUint:
6261 case glslang::EOpConvUint8ToInt:
6262 case glslang::EOpConvUint16ToInt:
6263 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006264 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006265 break;
6266 case glslang::EOpConvInt8ToUint64:
6267 case glslang::EOpConvInt16ToUint64:
6268 case glslang::EOpConvIntToUint64:
6269 case glslang::EOpConvUint8ToInt64:
6270 case glslang::EOpConvUint16ToInt64:
6271 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006272 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006273 break;
6274 default:
6275 assert(false && "Default missing");
6276 break;
6277 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006278 zero = makeSmearedConstant(zero, vectorSize);
6279 // Use OpIAdd, instead of OpBitcast to do the conversion when
6280 // generating for OpSpecConstantOp instruction.
6281 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6282 }
6283 // For normal run-time conversion instruction, use OpBitcast.
6284 convOp = spv::OpBitcast;
6285 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006286 case glslang::EOpConvUint64ToPtr:
6287 convOp = spv::OpConvertUToPtr;
6288 break;
6289 case glslang::EOpConvPtrToUint64:
6290 convOp = spv::OpConvertPtrToU;
6291 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006292 default:
6293 break;
6294 }
6295
6296 spv::Id result = 0;
6297 if (convOp == spv::OpNop)
6298 return result;
6299
6300 if (convOp == spv::OpSelect) {
6301 zero = makeSmearedConstant(zero, vectorSize);
6302 one = makeSmearedConstant(one, vectorSize);
6303 result = builder.createTriOp(convOp, destType, operand, one, zero);
6304 } else
6305 result = builder.createUnaryOp(convOp, destType, operand);
6306
John Kessenichead86222018-03-28 18:01:20 -06006307 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006308 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006309 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006310}
6311
6312spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6313{
6314 if (vectorSize == 0)
6315 return constant;
6316
6317 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6318 std::vector<spv::Id> components;
6319 for (int c = 0; c < vectorSize; ++c)
6320 components.push_back(constant);
6321 return builder.makeCompositeConstant(vectorTypeId, components);
6322}
6323
John Kessenich426394d2015-07-23 10:22:48 -06006324// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006325spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006326{
6327 spv::Op opCode = spv::OpNop;
6328
6329 switch (op) {
6330 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006331 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006332 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006333 opCode = spv::OpAtomicIAdd;
6334 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006335 case glslang::EOpAtomicCounterSubtract:
6336 opCode = spv::OpAtomicISub;
6337 break;
John Kessenich426394d2015-07-23 10:22:48 -06006338 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006339 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006340 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006341 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006342 break;
6343 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006344 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006345 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006346 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006347 break;
6348 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006349 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006350 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006351 opCode = spv::OpAtomicAnd;
6352 break;
6353 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006354 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006355 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006356 opCode = spv::OpAtomicOr;
6357 break;
6358 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006359 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006360 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006361 opCode = spv::OpAtomicXor;
6362 break;
6363 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006364 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006365 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006366 opCode = spv::OpAtomicExchange;
6367 break;
6368 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006369 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006370 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006371 opCode = spv::OpAtomicCompareExchange;
6372 break;
6373 case glslang::EOpAtomicCounterIncrement:
6374 opCode = spv::OpAtomicIIncrement;
6375 break;
6376 case glslang::EOpAtomicCounterDecrement:
6377 opCode = spv::OpAtomicIDecrement;
6378 break;
6379 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006380 case glslang::EOpImageAtomicLoad:
6381 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006382 opCode = spv::OpAtomicLoad;
6383 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 case glslang::EOpAtomicStore:
6385 case glslang::EOpImageAtomicStore:
6386 opCode = spv::OpAtomicStore;
6387 break;
John Kessenich426394d2015-07-23 10:22:48 -06006388 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006389 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006390 break;
6391 }
6392
Rex Xue8fe8b02017-09-26 15:42:56 +08006393 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6394 builder.addCapability(spv::CapabilityInt64Atomics);
6395
John Kessenich426394d2015-07-23 10:22:48 -06006396 // Sort out the operands
6397 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006398 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006399 // - compare-exchange swaps the value and comparator
6400 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006401 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006402 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6403 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6404 spv::Id scopeId;
6405 if (glslangIntermediate->usingVulkanMemoryModel()) {
6406 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6407 } else {
6408 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6409 }
6410 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006411 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006412 spv::Id semanticsId2 = semanticsId;
6413
6414 pointerId = operands[0];
6415 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6416 // no additional operands
6417 } else if (opCode == spv::OpAtomicCompareExchange) {
6418 compareId = operands[1];
6419 valueId = operands[2];
6420 if (operands.size() > 3) {
6421 scopeId = operands[3];
6422 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6423 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6424 }
6425 } else if (opCode == spv::OpAtomicLoad) {
6426 if (operands.size() > 1) {
6427 scopeId = operands[1];
6428 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6429 }
6430 } else {
6431 // atomic store or RMW
6432 valueId = operands[1];
6433 if (operands.size() > 2) {
6434 scopeId = operands[2];
6435 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6436 }
Rex Xu04db3f52015-09-16 11:44:02 +08006437 }
John Kessenich426394d2015-07-23 10:22:48 -06006438
Jeff Bolz36831c92018-09-05 10:11:41 -05006439 // Check for capabilities
6440 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006441 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6442 spv::MemorySemanticsMakeVisibleKHRMask |
6443 spv::MemorySemanticsOutputMemoryKHRMask |
6444 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006445 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6446 }
John Kessenich426394d2015-07-23 10:22:48 -06006447
Jeff Bolz36831c92018-09-05 10:11:41 -05006448 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6449 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6450 }
John Kessenich48d6e792017-10-06 21:21:48 -06006451
Jeff Bolz36831c92018-09-05 10:11:41 -05006452 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6453 spvAtomicOperands.push_back(pointerId);
6454 spvAtomicOperands.push_back(scopeId);
6455 spvAtomicOperands.push_back(semanticsId);
6456 if (opCode == spv::OpAtomicCompareExchange) {
6457 spvAtomicOperands.push_back(semanticsId2);
6458 spvAtomicOperands.push_back(valueId);
6459 spvAtomicOperands.push_back(compareId);
6460 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6461 spvAtomicOperands.push_back(valueId);
6462 }
John Kessenich48d6e792017-10-06 21:21:48 -06006463
Jeff Bolz36831c92018-09-05 10:11:41 -05006464 if (opCode == spv::OpAtomicStore) {
6465 builder.createNoResultOp(opCode, spvAtomicOperands);
6466 return 0;
6467 } else {
6468 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6469
6470 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6471 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6472 if (op == glslang::EOpAtomicCounterDecrement)
6473 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6474
6475 return resultId;
6476 }
John Kessenich426394d2015-07-23 10:22:48 -06006477}
6478
John Kessenich91cef522016-05-05 16:45:40 -06006479// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006480spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006481{
Corentin Walleze7061422018-08-08 15:20:15 +02006482#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006483 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6484 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006485#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006486
Rex Xu51596642016-09-21 18:56:12 +08006487 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006488 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006489 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6490
chaocf200da82016-12-20 12:44:35 -08006491 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6492 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006493 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6494 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006495 } else if (op == glslang::EOpAnyInvocation ||
6496 op == glslang::EOpAllInvocations ||
6497 op == glslang::EOpAllInvocationsEqual) {
6498 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6499 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006500 } else {
6501 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006502#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006503 if (op == glslang::EOpMinInvocationsNonUniform ||
6504 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006505 op == glslang::EOpAddInvocationsNonUniform ||
6506 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6507 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6508 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6509 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6510 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6511 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006512 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006513#endif
Rex Xu51596642016-09-21 18:56:12 +08006514
Rex Xu9d93a232016-05-05 12:30:44 +08006515#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006516 switch (op) {
6517 case glslang::EOpMinInvocations:
6518 case glslang::EOpMaxInvocations:
6519 case glslang::EOpAddInvocations:
6520 case glslang::EOpMinInvocationsNonUniform:
6521 case glslang::EOpMaxInvocationsNonUniform:
6522 case glslang::EOpAddInvocationsNonUniform:
6523 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006524 break;
6525 case glslang::EOpMinInvocationsInclusiveScan:
6526 case glslang::EOpMaxInvocationsInclusiveScan:
6527 case glslang::EOpAddInvocationsInclusiveScan:
6528 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6529 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6530 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6531 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006532 break;
6533 case glslang::EOpMinInvocationsExclusiveScan:
6534 case glslang::EOpMaxInvocationsExclusiveScan:
6535 case glslang::EOpAddInvocationsExclusiveScan:
6536 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6537 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6538 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6539 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006540 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006541 default:
6542 break;
Rex Xu430ef402016-10-14 17:22:23 +08006543 }
John Kessenich149afc32018-08-14 13:31:43 -06006544 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6545 spvGroupOperands.push_back(scope);
6546 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006547 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006548 spvGroupOperands.push_back(groupOp);
6549 }
Rex Xu9d93a232016-05-05 12:30:44 +08006550#endif
Rex Xu51596642016-09-21 18:56:12 +08006551 }
6552
John Kessenich149afc32018-08-14 13:31:43 -06006553 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6554 spv::IdImmediate op = { true, *opIt };
6555 spvGroupOperands.push_back(op);
6556 }
John Kessenich91cef522016-05-05 16:45:40 -06006557
6558 switch (op) {
6559 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006560 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006561 break;
John Kessenich91cef522016-05-05 16:45:40 -06006562 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006563 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006564 break;
John Kessenich91cef522016-05-05 16:45:40 -06006565 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006566 opCode = spv::OpSubgroupAllEqualKHR;
6567 break;
Rex Xu51596642016-09-21 18:56:12 +08006568 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006569 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006570 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006571 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006572 break;
6573 case glslang::EOpReadFirstInvocation:
6574 opCode = spv::OpSubgroupFirstInvocationKHR;
6575 break;
6576 case glslang::EOpBallot:
6577 {
6578 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6579 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6580 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6581 //
6582 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6583 //
6584 spv::Id uintType = builder.makeUintType(32);
6585 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6586 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6587
6588 std::vector<spv::Id> components;
6589 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6590 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6591
6592 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6593 return builder.createUnaryOp(spv::OpBitcast, typeId,
6594 builder.createCompositeConstruct(uvec2Type, components));
6595 }
6596
Rex Xu9d93a232016-05-05 12:30:44 +08006597#ifdef AMD_EXTENSIONS
6598 case glslang::EOpMinInvocations:
6599 case glslang::EOpMaxInvocations:
6600 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006601 case glslang::EOpMinInvocationsInclusiveScan:
6602 case glslang::EOpMaxInvocationsInclusiveScan:
6603 case glslang::EOpAddInvocationsInclusiveScan:
6604 case glslang::EOpMinInvocationsExclusiveScan:
6605 case glslang::EOpMaxInvocationsExclusiveScan:
6606 case glslang::EOpAddInvocationsExclusiveScan:
6607 if (op == glslang::EOpMinInvocations ||
6608 op == glslang::EOpMinInvocationsInclusiveScan ||
6609 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006610 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006611 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006612 else {
6613 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006614 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006615 else
Rex Xu51596642016-09-21 18:56:12 +08006616 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006617 }
Rex Xu430ef402016-10-14 17:22:23 +08006618 } else if (op == glslang::EOpMaxInvocations ||
6619 op == glslang::EOpMaxInvocationsInclusiveScan ||
6620 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006621 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006622 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006623 else {
6624 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006625 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006626 else
Rex Xu51596642016-09-21 18:56:12 +08006627 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006628 }
6629 } else {
6630 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006631 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006632 else
Rex Xu51596642016-09-21 18:56:12 +08006633 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006634 }
6635
Rex Xu2bbbe062016-08-23 15:41:05 +08006636 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006637 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006638
6639 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006640 case glslang::EOpMinInvocationsNonUniform:
6641 case glslang::EOpMaxInvocationsNonUniform:
6642 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006643 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6644 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6645 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6646 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6647 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6648 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6649 if (op == glslang::EOpMinInvocationsNonUniform ||
6650 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6651 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006652 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006653 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006654 else {
6655 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006656 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006657 else
Rex Xu51596642016-09-21 18:56:12 +08006658 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006659 }
6660 }
Rex Xu430ef402016-10-14 17:22:23 +08006661 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6662 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6663 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006664 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006665 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006666 else {
6667 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006668 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006669 else
Rex Xu51596642016-09-21 18:56:12 +08006670 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006671 }
6672 }
6673 else {
6674 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006675 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006676 else
Rex Xu51596642016-09-21 18:56:12 +08006677 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006678 }
6679
Rex Xu2bbbe062016-08-23 15:41:05 +08006680 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006681 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006682
6683 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006684#endif
John Kessenich91cef522016-05-05 16:45:40 -06006685 default:
6686 logger->missingFunctionality("invocation operation");
6687 return spv::NoResult;
6688 }
Rex Xu51596642016-09-21 18:56:12 +08006689
6690 assert(opCode != spv::OpNop);
6691 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006692}
6693
Rex Xu2bbbe062016-08-23 15:41:05 +08006694// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006695spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6696 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006697{
Rex Xub7072052016-09-26 15:53:40 +08006698#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006699 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6700 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006701 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006702 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006703 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6704 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6705 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006706#else
6707 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6708 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006709 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6710 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006711#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006712
6713 // Handle group invocation operations scalar by scalar.
6714 // The result type is the same type as the original type.
6715 // The algorithm is to:
6716 // - break the vector into scalars
6717 // - apply the operation to each scalar
6718 // - make a vector out the scalar results
6719
6720 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006721 int numComponents = builder.getNumComponents(operands[0]);
6722 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006723 std::vector<spv::Id> results;
6724
6725 // do each scalar op
6726 for (int comp = 0; comp < numComponents; ++comp) {
6727 std::vector<unsigned int> indexes;
6728 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006729 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6730 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006731 if (op == spv::OpSubgroupReadInvocationKHR) {
6732 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006733 spv::IdImmediate operand = { true, operands[1] };
6734 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006735 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006736 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6737 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006738 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006739 spv::IdImmediate operand = { true, operands[1] };
6740 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006741 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006742 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6743 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006744 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006745 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006746 spvGroupOperands.push_back(scalar);
6747 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006748
Rex Xub7072052016-09-26 15:53:40 +08006749 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006750 }
6751
6752 // put the pieces together
6753 return builder.createCompositeConstruct(typeId, results);
6754}
Rex Xu2bbbe062016-08-23 15:41:05 +08006755
John Kessenich66011cb2018-03-06 16:12:04 -07006756// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006757spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6758 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006759{
6760 // Add the required capabilities.
6761 switch (op) {
6762 case glslang::EOpSubgroupElect:
6763 builder.addCapability(spv::CapabilityGroupNonUniform);
6764 break;
6765 case glslang::EOpSubgroupAll:
6766 case glslang::EOpSubgroupAny:
6767 case glslang::EOpSubgroupAllEqual:
6768 builder.addCapability(spv::CapabilityGroupNonUniform);
6769 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6770 break;
6771 case glslang::EOpSubgroupBroadcast:
6772 case glslang::EOpSubgroupBroadcastFirst:
6773 case glslang::EOpSubgroupBallot:
6774 case glslang::EOpSubgroupInverseBallot:
6775 case glslang::EOpSubgroupBallotBitExtract:
6776 case glslang::EOpSubgroupBallotBitCount:
6777 case glslang::EOpSubgroupBallotInclusiveBitCount:
6778 case glslang::EOpSubgroupBallotExclusiveBitCount:
6779 case glslang::EOpSubgroupBallotFindLSB:
6780 case glslang::EOpSubgroupBallotFindMSB:
6781 builder.addCapability(spv::CapabilityGroupNonUniform);
6782 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6783 break;
6784 case glslang::EOpSubgroupShuffle:
6785 case glslang::EOpSubgroupShuffleXor:
6786 builder.addCapability(spv::CapabilityGroupNonUniform);
6787 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6788 break;
6789 case glslang::EOpSubgroupShuffleUp:
6790 case glslang::EOpSubgroupShuffleDown:
6791 builder.addCapability(spv::CapabilityGroupNonUniform);
6792 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6793 break;
6794 case glslang::EOpSubgroupAdd:
6795 case glslang::EOpSubgroupMul:
6796 case glslang::EOpSubgroupMin:
6797 case glslang::EOpSubgroupMax:
6798 case glslang::EOpSubgroupAnd:
6799 case glslang::EOpSubgroupOr:
6800 case glslang::EOpSubgroupXor:
6801 case glslang::EOpSubgroupInclusiveAdd:
6802 case glslang::EOpSubgroupInclusiveMul:
6803 case glslang::EOpSubgroupInclusiveMin:
6804 case glslang::EOpSubgroupInclusiveMax:
6805 case glslang::EOpSubgroupInclusiveAnd:
6806 case glslang::EOpSubgroupInclusiveOr:
6807 case glslang::EOpSubgroupInclusiveXor:
6808 case glslang::EOpSubgroupExclusiveAdd:
6809 case glslang::EOpSubgroupExclusiveMul:
6810 case glslang::EOpSubgroupExclusiveMin:
6811 case glslang::EOpSubgroupExclusiveMax:
6812 case glslang::EOpSubgroupExclusiveAnd:
6813 case glslang::EOpSubgroupExclusiveOr:
6814 case glslang::EOpSubgroupExclusiveXor:
6815 builder.addCapability(spv::CapabilityGroupNonUniform);
6816 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6817 break;
6818 case glslang::EOpSubgroupClusteredAdd:
6819 case glslang::EOpSubgroupClusteredMul:
6820 case glslang::EOpSubgroupClusteredMin:
6821 case glslang::EOpSubgroupClusteredMax:
6822 case glslang::EOpSubgroupClusteredAnd:
6823 case glslang::EOpSubgroupClusteredOr:
6824 case glslang::EOpSubgroupClusteredXor:
6825 builder.addCapability(spv::CapabilityGroupNonUniform);
6826 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6827 break;
6828 case glslang::EOpSubgroupQuadBroadcast:
6829 case glslang::EOpSubgroupQuadSwapHorizontal:
6830 case glslang::EOpSubgroupQuadSwapVertical:
6831 case glslang::EOpSubgroupQuadSwapDiagonal:
6832 builder.addCapability(spv::CapabilityGroupNonUniform);
6833 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6834 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006835#ifdef NV_EXTENSIONS
6836 case glslang::EOpSubgroupPartitionedAdd:
6837 case glslang::EOpSubgroupPartitionedMul:
6838 case glslang::EOpSubgroupPartitionedMin:
6839 case glslang::EOpSubgroupPartitionedMax:
6840 case glslang::EOpSubgroupPartitionedAnd:
6841 case glslang::EOpSubgroupPartitionedOr:
6842 case glslang::EOpSubgroupPartitionedXor:
6843 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6844 case glslang::EOpSubgroupPartitionedInclusiveMul:
6845 case glslang::EOpSubgroupPartitionedInclusiveMin:
6846 case glslang::EOpSubgroupPartitionedInclusiveMax:
6847 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6848 case glslang::EOpSubgroupPartitionedInclusiveOr:
6849 case glslang::EOpSubgroupPartitionedInclusiveXor:
6850 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6851 case glslang::EOpSubgroupPartitionedExclusiveMul:
6852 case glslang::EOpSubgroupPartitionedExclusiveMin:
6853 case glslang::EOpSubgroupPartitionedExclusiveMax:
6854 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6855 case glslang::EOpSubgroupPartitionedExclusiveOr:
6856 case glslang::EOpSubgroupPartitionedExclusiveXor:
6857 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6858 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6859 break;
6860#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006861 default: assert(0 && "Unhandled subgroup operation!");
6862 }
6863
6864 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6865 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6866 const bool isBool = typeProxy == glslang::EbtBool;
6867
6868 spv::Op opCode = spv::OpNop;
6869
6870 // Figure out which opcode to use.
6871 switch (op) {
6872 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6873 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6874 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6875 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6876 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6877 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6878 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6879 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6880 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6881 case glslang::EOpSubgroupBallotBitCount:
6882 case glslang::EOpSubgroupBallotInclusiveBitCount:
6883 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6884 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6885 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6886 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6887 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6888 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6889 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6890 case glslang::EOpSubgroupAdd:
6891 case glslang::EOpSubgroupInclusiveAdd:
6892 case glslang::EOpSubgroupExclusiveAdd:
6893 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006894#ifdef NV_EXTENSIONS
6895 case glslang::EOpSubgroupPartitionedAdd:
6896 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6897 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6898#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006899 if (isFloat) {
6900 opCode = spv::OpGroupNonUniformFAdd;
6901 } else {
6902 opCode = spv::OpGroupNonUniformIAdd;
6903 }
6904 break;
6905 case glslang::EOpSubgroupMul:
6906 case glslang::EOpSubgroupInclusiveMul:
6907 case glslang::EOpSubgroupExclusiveMul:
6908 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006909#ifdef NV_EXTENSIONS
6910 case glslang::EOpSubgroupPartitionedMul:
6911 case glslang::EOpSubgroupPartitionedInclusiveMul:
6912 case glslang::EOpSubgroupPartitionedExclusiveMul:
6913#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006914 if (isFloat) {
6915 opCode = spv::OpGroupNonUniformFMul;
6916 } else {
6917 opCode = spv::OpGroupNonUniformIMul;
6918 }
6919 break;
6920 case glslang::EOpSubgroupMin:
6921 case glslang::EOpSubgroupInclusiveMin:
6922 case glslang::EOpSubgroupExclusiveMin:
6923 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006924#ifdef NV_EXTENSIONS
6925 case glslang::EOpSubgroupPartitionedMin:
6926 case glslang::EOpSubgroupPartitionedInclusiveMin:
6927 case glslang::EOpSubgroupPartitionedExclusiveMin:
6928#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006929 if (isFloat) {
6930 opCode = spv::OpGroupNonUniformFMin;
6931 } else if (isUnsigned) {
6932 opCode = spv::OpGroupNonUniformUMin;
6933 } else {
6934 opCode = spv::OpGroupNonUniformSMin;
6935 }
6936 break;
6937 case glslang::EOpSubgroupMax:
6938 case glslang::EOpSubgroupInclusiveMax:
6939 case glslang::EOpSubgroupExclusiveMax:
6940 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006941#ifdef NV_EXTENSIONS
6942 case glslang::EOpSubgroupPartitionedMax:
6943 case glslang::EOpSubgroupPartitionedInclusiveMax:
6944 case glslang::EOpSubgroupPartitionedExclusiveMax:
6945#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006946 if (isFloat) {
6947 opCode = spv::OpGroupNonUniformFMax;
6948 } else if (isUnsigned) {
6949 opCode = spv::OpGroupNonUniformUMax;
6950 } else {
6951 opCode = spv::OpGroupNonUniformSMax;
6952 }
6953 break;
6954 case glslang::EOpSubgroupAnd:
6955 case glslang::EOpSubgroupInclusiveAnd:
6956 case glslang::EOpSubgroupExclusiveAnd:
6957 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006958#ifdef NV_EXTENSIONS
6959 case glslang::EOpSubgroupPartitionedAnd:
6960 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6961 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6962#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006963 if (isBool) {
6964 opCode = spv::OpGroupNonUniformLogicalAnd;
6965 } else {
6966 opCode = spv::OpGroupNonUniformBitwiseAnd;
6967 }
6968 break;
6969 case glslang::EOpSubgroupOr:
6970 case glslang::EOpSubgroupInclusiveOr:
6971 case glslang::EOpSubgroupExclusiveOr:
6972 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006973#ifdef NV_EXTENSIONS
6974 case glslang::EOpSubgroupPartitionedOr:
6975 case glslang::EOpSubgroupPartitionedInclusiveOr:
6976 case glslang::EOpSubgroupPartitionedExclusiveOr:
6977#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006978 if (isBool) {
6979 opCode = spv::OpGroupNonUniformLogicalOr;
6980 } else {
6981 opCode = spv::OpGroupNonUniformBitwiseOr;
6982 }
6983 break;
6984 case glslang::EOpSubgroupXor:
6985 case glslang::EOpSubgroupInclusiveXor:
6986 case glslang::EOpSubgroupExclusiveXor:
6987 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006988#ifdef NV_EXTENSIONS
6989 case glslang::EOpSubgroupPartitionedXor:
6990 case glslang::EOpSubgroupPartitionedInclusiveXor:
6991 case glslang::EOpSubgroupPartitionedExclusiveXor:
6992#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006993 if (isBool) {
6994 opCode = spv::OpGroupNonUniformLogicalXor;
6995 } else {
6996 opCode = spv::OpGroupNonUniformBitwiseXor;
6997 }
6998 break;
6999 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7000 case glslang::EOpSubgroupQuadSwapHorizontal:
7001 case glslang::EOpSubgroupQuadSwapVertical:
7002 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7003 default: assert(0 && "Unhandled subgroup operation!");
7004 }
7005
John Kessenich149afc32018-08-14 13:31:43 -06007006 // get the right Group Operation
7007 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007008 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007009 default:
7010 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007011 case glslang::EOpSubgroupBallotBitCount:
7012 case glslang::EOpSubgroupAdd:
7013 case glslang::EOpSubgroupMul:
7014 case glslang::EOpSubgroupMin:
7015 case glslang::EOpSubgroupMax:
7016 case glslang::EOpSubgroupAnd:
7017 case glslang::EOpSubgroupOr:
7018 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007019 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007020 break;
7021 case glslang::EOpSubgroupBallotInclusiveBitCount:
7022 case glslang::EOpSubgroupInclusiveAdd:
7023 case glslang::EOpSubgroupInclusiveMul:
7024 case glslang::EOpSubgroupInclusiveMin:
7025 case glslang::EOpSubgroupInclusiveMax:
7026 case glslang::EOpSubgroupInclusiveAnd:
7027 case glslang::EOpSubgroupInclusiveOr:
7028 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007029 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007030 break;
7031 case glslang::EOpSubgroupBallotExclusiveBitCount:
7032 case glslang::EOpSubgroupExclusiveAdd:
7033 case glslang::EOpSubgroupExclusiveMul:
7034 case glslang::EOpSubgroupExclusiveMin:
7035 case glslang::EOpSubgroupExclusiveMax:
7036 case glslang::EOpSubgroupExclusiveAnd:
7037 case glslang::EOpSubgroupExclusiveOr:
7038 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007039 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007040 break;
7041 case glslang::EOpSubgroupClusteredAdd:
7042 case glslang::EOpSubgroupClusteredMul:
7043 case glslang::EOpSubgroupClusteredMin:
7044 case glslang::EOpSubgroupClusteredMax:
7045 case glslang::EOpSubgroupClusteredAnd:
7046 case glslang::EOpSubgroupClusteredOr:
7047 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007048 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007049 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007050#ifdef NV_EXTENSIONS
7051 case glslang::EOpSubgroupPartitionedAdd:
7052 case glslang::EOpSubgroupPartitionedMul:
7053 case glslang::EOpSubgroupPartitionedMin:
7054 case glslang::EOpSubgroupPartitionedMax:
7055 case glslang::EOpSubgroupPartitionedAnd:
7056 case glslang::EOpSubgroupPartitionedOr:
7057 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007058 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007059 break;
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:
John Kessenich149afc32018-08-14 13:31:43 -06007067 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007068 break;
7069 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7070 case glslang::EOpSubgroupPartitionedExclusiveMul:
7071 case glslang::EOpSubgroupPartitionedExclusiveMin:
7072 case glslang::EOpSubgroupPartitionedExclusiveMax:
7073 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7074 case glslang::EOpSubgroupPartitionedExclusiveOr:
7075 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007076 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007077 break;
7078#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007079 }
7080
John Kessenich149afc32018-08-14 13:31:43 -06007081 // build the instruction
7082 std::vector<spv::IdImmediate> spvGroupOperands;
7083
7084 // Every operation begins with the Execution Scope operand.
7085 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7086 spvGroupOperands.push_back(executionScope);
7087
7088 // Next, for all operations that use a Group Operation, push that as an operand.
7089 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007090 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007091 spvGroupOperands.push_back(groupOperand);
7092 }
7093
John Kessenich66011cb2018-03-06 16:12:04 -07007094 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007095 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7096 spv::IdImmediate operand = { true, *opIt };
7097 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007098 }
7099
7100 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007101 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007102 switch (op) {
7103 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007104 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7105 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7106 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7107 }
7108 if (directionId != spv::NoResult) {
7109 spv::IdImmediate direction = { true, directionId };
7110 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007111 }
7112
7113 return builder.createOp(opCode, typeId, spvGroupOperands);
7114}
7115
John Kessenich5e4b1242015-08-06 22:53:06 -06007116spv::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 -06007117{
John Kessenich66011cb2018-03-06 16:12:04 -07007118 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7119 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007120
John Kessenich140f3df2015-06-26 16:58:36 -06007121 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007122 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007123 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007124 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007125 spv::Id typeId0 = 0;
7126 if (consumedOperands > 0)
7127 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007128 spv::Id typeId1 = 0;
7129 if (consumedOperands > 1)
7130 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007131 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007132
7133 switch (op) {
7134 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007135 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007136 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007137 else if (isUnsigned)
7138 libCall = spv::GLSLstd450UMin;
7139 else
7140 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007141 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007142 break;
7143 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007144 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007145 break;
7146 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007147 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007148 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007149 else if (isUnsigned)
7150 libCall = spv::GLSLstd450UMax;
7151 else
7152 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007153 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007154 break;
7155 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007157 break;
7158 case glslang::EOpDot:
7159 opCode = spv::OpDot;
7160 break;
7161 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007162 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164
7165 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007166 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007167 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 else if (isUnsigned)
7169 libCall = spv::GLSLstd450UClamp;
7170 else
7171 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007172 builder.promoteScalar(precision, operands.front(), operands[1]);
7173 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007174 break;
7175 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007176 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7177 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007178 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007179 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007180 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007181 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007182 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007183 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007184 break;
7185 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007186 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007187 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007188 break;
7189 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007190 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007191 builder.promoteScalar(precision, operands[0], operands[2]);
7192 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007193 break;
7194
7195 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007196 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007197 break;
7198 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007199 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007200 break;
7201 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007202 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007203 break;
7204 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007205 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007206 break;
7207 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007208 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007209 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007210 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007211#ifdef AMD_EXTENSIONS
7212 if (typeProxy == glslang::EbtFloat16)
7213 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7214#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007215 libCall = spv::GLSLstd450InterpolateAtSample;
7216 break;
7217 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007218#ifdef AMD_EXTENSIONS
7219 if (typeProxy == glslang::EbtFloat16)
7220 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7221#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007222 libCall = spv::GLSLstd450InterpolateAtOffset;
7223 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007224 case glslang::EOpAddCarry:
7225 opCode = spv::OpIAddCarry;
7226 typeId = builder.makeStructResultType(typeId0, typeId0);
7227 consumedOperands = 2;
7228 break;
7229 case glslang::EOpSubBorrow:
7230 opCode = spv::OpISubBorrow;
7231 typeId = builder.makeStructResultType(typeId0, typeId0);
7232 consumedOperands = 2;
7233 break;
7234 case glslang::EOpUMulExtended:
7235 opCode = spv::OpUMulExtended;
7236 typeId = builder.makeStructResultType(typeId0, typeId0);
7237 consumedOperands = 2;
7238 break;
7239 case glslang::EOpIMulExtended:
7240 opCode = spv::OpSMulExtended;
7241 typeId = builder.makeStructResultType(typeId0, typeId0);
7242 consumedOperands = 2;
7243 break;
7244 case glslang::EOpBitfieldExtract:
7245 if (isUnsigned)
7246 opCode = spv::OpBitFieldUExtract;
7247 else
7248 opCode = spv::OpBitFieldSExtract;
7249 break;
7250 case glslang::EOpBitfieldInsert:
7251 opCode = spv::OpBitFieldInsert;
7252 break;
7253
7254 case glslang::EOpFma:
7255 libCall = spv::GLSLstd450Fma;
7256 break;
7257 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007258 {
7259 libCall = spv::GLSLstd450FrexpStruct;
7260 assert(builder.isPointerType(typeId1));
7261 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007262 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007263#ifdef AMD_EXTENSIONS
7264 if (width == 16)
7265 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7266 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7267#endif
Rex Xu470026f2017-03-29 17:12:40 +08007268 if (builder.getNumComponents(operands[0]) == 1)
7269 frexpIntType = builder.makeIntegerType(width, true);
7270 else
7271 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7272 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7273 consumedOperands = 1;
7274 }
John Kessenich55e7d112015-11-15 21:33:39 -07007275 break;
7276 case glslang::EOpLdexp:
7277 libCall = spv::GLSLstd450Ldexp;
7278 break;
7279
Rex Xu574ab042016-04-14 16:53:07 +08007280 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007281 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007282
John Kessenich66011cb2018-03-06 16:12:04 -07007283 case glslang::EOpSubgroupBroadcast:
7284 case glslang::EOpSubgroupBallotBitExtract:
7285 case glslang::EOpSubgroupShuffle:
7286 case glslang::EOpSubgroupShuffleXor:
7287 case glslang::EOpSubgroupShuffleUp:
7288 case glslang::EOpSubgroupShuffleDown:
7289 case glslang::EOpSubgroupClusteredAdd:
7290 case glslang::EOpSubgroupClusteredMul:
7291 case glslang::EOpSubgroupClusteredMin:
7292 case glslang::EOpSubgroupClusteredMax:
7293 case glslang::EOpSubgroupClusteredAnd:
7294 case glslang::EOpSubgroupClusteredOr:
7295 case glslang::EOpSubgroupClusteredXor:
7296 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007297#ifdef NV_EXTENSIONS
7298 case glslang::EOpSubgroupPartitionedAdd:
7299 case glslang::EOpSubgroupPartitionedMul:
7300 case glslang::EOpSubgroupPartitionedMin:
7301 case glslang::EOpSubgroupPartitionedMax:
7302 case glslang::EOpSubgroupPartitionedAnd:
7303 case glslang::EOpSubgroupPartitionedOr:
7304 case glslang::EOpSubgroupPartitionedXor:
7305 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7306 case glslang::EOpSubgroupPartitionedInclusiveMul:
7307 case glslang::EOpSubgroupPartitionedInclusiveMin:
7308 case glslang::EOpSubgroupPartitionedInclusiveMax:
7309 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7310 case glslang::EOpSubgroupPartitionedInclusiveOr:
7311 case glslang::EOpSubgroupPartitionedInclusiveXor:
7312 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7313 case glslang::EOpSubgroupPartitionedExclusiveMul:
7314 case glslang::EOpSubgroupPartitionedExclusiveMin:
7315 case glslang::EOpSubgroupPartitionedExclusiveMax:
7316 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7317 case glslang::EOpSubgroupPartitionedExclusiveOr:
7318 case glslang::EOpSubgroupPartitionedExclusiveXor:
7319#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007320 return createSubgroupOperation(op, typeId, operands, typeProxy);
7321
Rex Xu9d93a232016-05-05 12:30:44 +08007322#ifdef AMD_EXTENSIONS
7323 case glslang::EOpSwizzleInvocations:
7324 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7325 libCall = spv::SwizzleInvocationsAMD;
7326 break;
7327 case glslang::EOpSwizzleInvocationsMasked:
7328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7329 libCall = spv::SwizzleInvocationsMaskedAMD;
7330 break;
7331 case glslang::EOpWriteInvocation:
7332 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7333 libCall = spv::WriteInvocationAMD;
7334 break;
7335
7336 case glslang::EOpMin3:
7337 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7338 if (isFloat)
7339 libCall = spv::FMin3AMD;
7340 else {
7341 if (isUnsigned)
7342 libCall = spv::UMin3AMD;
7343 else
7344 libCall = spv::SMin3AMD;
7345 }
7346 break;
7347 case glslang::EOpMax3:
7348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7349 if (isFloat)
7350 libCall = spv::FMax3AMD;
7351 else {
7352 if (isUnsigned)
7353 libCall = spv::UMax3AMD;
7354 else
7355 libCall = spv::SMax3AMD;
7356 }
7357 break;
7358 case glslang::EOpMid3:
7359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7360 if (isFloat)
7361 libCall = spv::FMid3AMD;
7362 else {
7363 if (isUnsigned)
7364 libCall = spv::UMid3AMD;
7365 else
7366 libCall = spv::SMid3AMD;
7367 }
7368 break;
7369
7370 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007371 if (typeProxy == glslang::EbtFloat16)
7372 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007373 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7374 libCall = spv::InterpolateAtVertexAMD;
7375 break;
7376#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007377 case glslang::EOpBarrier:
7378 {
7379 // This is for the extended controlBarrier function, with four operands.
7380 // The unextended barrier() goes through createNoArgOperation.
7381 assert(operands.size() == 4);
7382 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7383 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7384 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7385 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007386 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7387 spv::MemorySemanticsMakeVisibleKHRMask |
7388 spv::MemorySemanticsOutputMemoryKHRMask |
7389 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007390 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7391 }
7392 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7393 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7394 }
7395 return 0;
7396 }
7397 break;
7398 case glslang::EOpMemoryBarrier:
7399 {
7400 // This is for the extended memoryBarrier function, with three operands.
7401 // The unextended memoryBarrier() goes through createNoArgOperation.
7402 assert(operands.size() == 3);
7403 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7404 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7405 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007406 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7407 spv::MemorySemanticsMakeVisibleKHRMask |
7408 spv::MemorySemanticsOutputMemoryKHRMask |
7409 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007410 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7411 }
7412 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7413 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7414 }
7415 return 0;
7416 }
7417 break;
Chao Chen3c366992018-09-19 11:41:59 -07007418
7419#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007420 case glslang::EOpReportIntersectionNV:
7421 {
7422 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007423 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007424 }
7425 break;
7426 case glslang::EOpTraceNV:
7427 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007428 builder.createNoResultOp(spv::OpTraceNV, operands);
7429 return 0;
7430 }
7431 break;
7432 case glslang::EOpExecuteCallableNV:
7433 {
7434 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007435 return 0;
7436 }
7437 break;
Chao Chen3c366992018-09-19 11:41:59 -07007438 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7439 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7440 return 0;
7441#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007442 case glslang::EOpCooperativeMatrixMulAdd:
7443 opCode = spv::OpCooperativeMatrixMulAddNV;
7444 break;
7445
John Kessenich140f3df2015-06-26 16:58:36 -06007446 default:
7447 return 0;
7448 }
7449
7450 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007451 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007452 // Use an extended instruction from the standard library.
7453 // Construct the call arguments, without modifying the original operands vector.
7454 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7455 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007456 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007457 } else if (opCode == spv::OpDot && !isFloat) {
7458 // int dot(int, int)
7459 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7460 const int componentCount = builder.getNumComponents(operands[0]);
7461 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7462 builder.setPrecision(mulOp, precision);
7463 id = builder.createCompositeExtract(mulOp, typeId, 0);
7464 for (int i = 1; i < componentCount; ++i) {
7465 builder.setPrecision(id, precision);
7466 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7467 }
John Kessenich2359bd02015-12-06 19:29:11 -07007468 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007469 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007470 case 0:
7471 // should all be handled by visitAggregate and createNoArgOperation
7472 assert(0);
7473 return 0;
7474 case 1:
7475 // should all be handled by createUnaryOperation
7476 assert(0);
7477 return 0;
7478 case 2:
7479 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7480 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007481 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007482 // anything 3 or over doesn't have l-value operands, so all should be consumed
7483 assert(consumedOperands == operands.size());
7484 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007485 break;
7486 }
7487 }
7488
John Kessenich55e7d112015-11-15 21:33:39 -07007489 // Decode the return types that were structures
7490 switch (op) {
7491 case glslang::EOpAddCarry:
7492 case glslang::EOpSubBorrow:
7493 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7494 id = builder.createCompositeExtract(id, typeId0, 0);
7495 break;
7496 case glslang::EOpUMulExtended:
7497 case glslang::EOpIMulExtended:
7498 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7499 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7500 break;
7501 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007502 {
7503 assert(operands.size() == 2);
7504 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7505 // "exp" is floating-point type (from HLSL intrinsic)
7506 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7507 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7508 builder.createStore(member1, operands[1]);
7509 } else
7510 // "exp" is integer type (from GLSL built-in function)
7511 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7512 id = builder.createCompositeExtract(id, typeId0, 0);
7513 }
John Kessenich55e7d112015-11-15 21:33:39 -07007514 break;
7515 default:
7516 break;
7517 }
7518
John Kessenich32cfd492016-02-02 12:37:46 -07007519 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007520}
7521
Rex Xu9d93a232016-05-05 12:30:44 +08007522// Intrinsics with no arguments (or no return value, and no precision).
7523spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007524{
Jeff Bolz36831c92018-09-05 10:11:41 -05007525 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7526 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007527
7528 switch (op) {
7529 case glslang::EOpEmitVertex:
7530 builder.createNoResultOp(spv::OpEmitVertex);
7531 return 0;
7532 case glslang::EOpEndPrimitive:
7533 builder.createNoResultOp(spv::OpEndPrimitive);
7534 return 0;
7535 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007536 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007537 if (glslangIntermediate->usingVulkanMemoryModel()) {
7538 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7539 spv::MemorySemanticsOutputMemoryKHRMask |
7540 spv::MemorySemanticsAcquireReleaseMask);
7541 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7542 } else {
7543 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7544 }
John Kessenich82979362017-12-11 04:02:24 -07007545 } else {
7546 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7547 spv::MemorySemanticsWorkgroupMemoryMask |
7548 spv::MemorySemanticsAcquireReleaseMask);
7549 }
John Kessenich140f3df2015-06-26 16:58:36 -06007550 return 0;
7551 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007552 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7553 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007554 return 0;
7555 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007556 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7557 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007558 return 0;
7559 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007560 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7561 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007562 return 0;
7563 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007564 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7565 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007566 return 0;
7567 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007568 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7569 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007570 return 0;
7571 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007572 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7573 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007574 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007575 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007576 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007577 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007578 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007579 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007580 case glslang::EOpDeviceMemoryBarrier:
7581 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7582 spv::MemorySemanticsImageMemoryMask |
7583 spv::MemorySemanticsAcquireReleaseMask);
7584 return 0;
7585 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7586 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7587 spv::MemorySemanticsImageMemoryMask |
7588 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007589 return 0;
7590 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007591 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7592 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007593 return 0;
7594 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007595 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7596 spv::MemorySemanticsWorkgroupMemoryMask |
7597 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007598 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007599 case glslang::EOpSubgroupBarrier:
7600 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7601 spv::MemorySemanticsAcquireReleaseMask);
7602 return spv::NoResult;
7603 case glslang::EOpSubgroupMemoryBarrier:
7604 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7605 spv::MemorySemanticsAcquireReleaseMask);
7606 return spv::NoResult;
7607 case glslang::EOpSubgroupMemoryBarrierBuffer:
7608 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7609 spv::MemorySemanticsAcquireReleaseMask);
7610 return spv::NoResult;
7611 case glslang::EOpSubgroupMemoryBarrierImage:
7612 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7613 spv::MemorySemanticsAcquireReleaseMask);
7614 return spv::NoResult;
7615 case glslang::EOpSubgroupMemoryBarrierShared:
7616 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7617 spv::MemorySemanticsAcquireReleaseMask);
7618 return spv::NoResult;
7619 case glslang::EOpSubgroupElect: {
7620 std::vector<spv::Id> operands;
7621 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7622 }
Rex Xu9d93a232016-05-05 12:30:44 +08007623#ifdef AMD_EXTENSIONS
7624 case glslang::EOpTime:
7625 {
7626 std::vector<spv::Id> args; // Dummy arguments
7627 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7628 return builder.setPrecision(id, precision);
7629 }
7630#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007631#ifdef NV_EXTENSIONS
7632 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007633 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007634 return 0;
7635 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007636 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007637 return 0;
7638#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007639
7640 case glslang::EOpBeginInvocationInterlock:
7641 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7642 return 0;
7643 case glslang::EOpEndInvocationInterlock:
7644 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7645 return 0;
7646
John Kessenich140f3df2015-06-26 16:58:36 -06007647 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007648 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007649 return 0;
7650 }
7651}
7652
7653spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7654{
John Kessenich2f273362015-07-18 22:34:27 -06007655 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007656 spv::Id id;
7657 if (symbolValues.end() != iter) {
7658 id = iter->second;
7659 return id;
7660 }
7661
7662 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007663 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7664 auto forcedType = getForcedType(builtIn, symbol->getType());
7665 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007666 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007667 if (forcedType.second != spv::NoType)
7668 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007669
Rex Xuc884b4a2016-06-29 15:03:44 +08007670 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007671 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7672 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7673 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007674#ifdef NV_EXTENSIONS
7675 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7676#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007677 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007678 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007679 if (symbol->getQualifier().hasIndex())
7680 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7681 if (symbol->getQualifier().hasComponent())
7682 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007683 // atomic counters use this:
7684 if (symbol->getQualifier().hasOffset())
7685 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007686 }
7687
scygan2c864272016-05-18 18:09:17 +02007688 if (symbol->getQualifier().hasLocation())
7689 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007690 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007691 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007692 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007693 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007694 }
John Kessenich140f3df2015-06-26 16:58:36 -06007695 if (symbol->getQualifier().hasSet())
7696 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007697 else if (IsDescriptorResource(symbol->getType())) {
7698 // default to 0
7699 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7700 }
John Kessenich140f3df2015-06-26 16:58:36 -06007701 if (symbol->getQualifier().hasBinding())
7702 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007703 else if (IsDescriptorResource(symbol->getType())) {
7704 // default to 0
7705 builder.addDecoration(id, spv::DecorationBinding, 0);
7706 }
John Kessenich6c292d32016-02-15 20:58:50 -07007707 if (symbol->getQualifier().hasAttachment())
7708 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007709 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007710 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007711 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007712 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007713 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7714 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7715 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7716 }
7717 if (symbol->getQualifier().hasXfbOffset())
7718 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007719 }
7720
Rex Xu1da878f2016-02-21 20:59:01 +08007721 if (symbol->getType().isImage()) {
7722 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007723 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007724 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007725 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007726 }
7727
John Kessenich9c14f772019-06-17 08:38:35 -06007728 // add built-in variable decoration
7729 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007730 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007731 }
John Kessenich140f3df2015-06-26 16:58:36 -06007732
John Kessenich5611c6d2018-04-05 11:25:02 -06007733 // nonuniform
7734 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7735
John Kessenichecba76f2017-01-06 00:34:48 -07007736#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007737 if (builtIn == spv::BuiltInSampleMask) {
7738 spv::Decoration decoration;
7739 // GL_NV_sample_mask_override_coverage extension
7740 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007741 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007742 else
7743 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007744 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007745 if (decoration != spv::DecorationMax) {
7746 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7747 }
7748 }
chaoc771d89f2017-01-13 01:10:53 -08007749 else if (builtIn == spv::BuiltInLayer) {
7750 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007751 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007752 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007753 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7754 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7755 }
John Kessenichb41bff62017-08-11 13:07:17 -06007756 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007757 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7758 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007759 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7760 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7761 }
7762 }
7763
chaoc6e5acae2016-12-20 13:28:52 -08007764 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007765 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007766 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007767 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7768 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007769 if (symbol->getQualifier().pervertexNV) {
7770 builder.addDecoration(id, spv::DecorationPerVertexNV);
7771 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7772 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7773 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007774#endif
7775
John Kessenich5d610ee2018-03-07 18:05:55 -07007776 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7777 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7778 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7779 symbol->getType().getQualifier().semanticName);
7780 }
7781
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007782 if (symbol->getBasicType() == glslang::EbtReference) {
7783 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7784 }
7785
John Kessenich140f3df2015-06-26 16:58:36 -06007786 return id;
7787}
7788
Chao Chen3c366992018-09-19 11:41:59 -07007789#ifdef NV_EXTENSIONS
7790// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7791void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7792{
7793 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007794 if (qualifier.perPrimitiveNV) {
7795 // Need to add capability/extension for fragment shader.
7796 // Mesh shader already adds this by default.
7797 if (glslangIntermediate->getStage() == EShLangFragment) {
7798 builder.addCapability(spv::CapabilityMeshShadingNV);
7799 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7800 }
Chao Chen3c366992018-09-19 11:41:59 -07007801 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007802 }
Chao Chen3c366992018-09-19 11:41:59 -07007803 if (qualifier.perViewNV)
7804 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7805 if (qualifier.perTaskNV)
7806 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7807 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007808 if (qualifier.perPrimitiveNV) {
7809 // Need to add capability/extension for fragment shader.
7810 // Mesh shader already adds this by default.
7811 if (glslangIntermediate->getStage() == EShLangFragment) {
7812 builder.addCapability(spv::CapabilityMeshShadingNV);
7813 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7814 }
Chao Chen3c366992018-09-19 11:41:59 -07007815 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007816 }
Chao Chen3c366992018-09-19 11:41:59 -07007817 if (qualifier.perViewNV)
7818 builder.addDecoration(id, spv::DecorationPerViewNV);
7819 if (qualifier.perTaskNV)
7820 builder.addDecoration(id, spv::DecorationPerTaskNV);
7821 }
7822}
7823#endif
7824
John Kessenich55e7d112015-11-15 21:33:39 -07007825// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007826// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007827//
7828// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7829//
7830// Recursively walk the nodes. The nodes form a tree whose leaves are
7831// regular constants, which themselves are trees that createSpvConstant()
7832// recursively walks. So, this function walks the "top" of the tree:
7833// - emit specialization constant-building instructions for specConstant
7834// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007835spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007836{
John Kessenich7cc0e282016-03-20 00:46:02 -06007837 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007838
qining4f4bb812016-04-03 23:55:17 -04007839 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007840 if (! node.getQualifier().specConstant) {
7841 // hand off to the non-spec-constant path
7842 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7843 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007844 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007845 nextConst, false);
7846 }
7847
7848 // We now know we have a specialization constant to build
7849
John Kessenichd94c0032016-05-30 19:29:40 -06007850 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007851 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7852 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7853 std::vector<spv::Id> dimConstId;
7854 for (int dim = 0; dim < 3; ++dim) {
7855 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7856 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007857 if (specConst) {
7858 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7859 glslangIntermediate->getLocalSizeSpecId(dim));
7860 }
qining4f4bb812016-04-03 23:55:17 -04007861 }
7862 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7863 }
7864
7865 // An AST node labelled as specialization constant should be a symbol node.
7866 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7867 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007868 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007869 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007870 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7871 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7872 // will set the builder into spec constant op instruction generating mode.
7873 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007874 result = accessChainLoad(sub_tree->getType());
7875 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007876 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007877 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007878 } else {
7879 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007880 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007881 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007882 builder.addName(result, sn->getName().c_str());
7883 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007884 }
qining4f4bb812016-04-03 23:55:17 -04007885
7886 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7887 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007888 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007889 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007890}
7891
John Kessenich140f3df2015-06-26 16:58:36 -06007892// Use 'consts' as the flattened glslang source of scalar constants to recursively
7893// build the aggregate SPIR-V constant.
7894//
7895// If there are not enough elements present in 'consts', 0 will be substituted;
7896// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7897//
qining08408382016-03-21 09:51:37 -04007898spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007899{
7900 // vector of constants for SPIR-V
7901 std::vector<spv::Id> spvConsts;
7902
7903 // Type is used for struct and array constants
7904 spv::Id typeId = convertGlslangToSpvType(glslangType);
7905
7906 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007907 glslang::TType elementType(glslangType, 0);
7908 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007909 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007910 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007911 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007912 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007913 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007914 } else if (glslangType.isCoopMat()) {
7915 glslang::TType componentType(glslangType.getBasicType());
7916 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007917 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007918 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7919 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007920 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007921 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007922 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7923 bool zero = nextConst >= consts.size();
7924 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007925 case glslang::EbtInt8:
7926 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7927 break;
7928 case glslang::EbtUint8:
7929 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7930 break;
7931 case glslang::EbtInt16:
7932 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7933 break;
7934 case glslang::EbtUint16:
7935 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007937 case glslang::EbtInt:
7938 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7939 break;
7940 case glslang::EbtUint:
7941 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7942 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007943 case glslang::EbtInt64:
7944 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7945 break;
7946 case glslang::EbtUint64:
7947 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007949 case glslang::EbtFloat:
7950 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7951 break;
7952 case glslang::EbtDouble:
7953 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7954 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007955 case glslang::EbtFloat16:
7956 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7957 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007958 case glslang::EbtBool:
7959 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7960 break;
7961 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007962 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007963 break;
7964 }
7965 ++nextConst;
7966 }
7967 } else {
7968 // we have a non-aggregate (scalar) constant
7969 bool zero = nextConst >= consts.size();
7970 spv::Id scalar = 0;
7971 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007972 case glslang::EbtInt8:
7973 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7974 break;
7975 case glslang::EbtUint8:
7976 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7977 break;
7978 case glslang::EbtInt16:
7979 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7980 break;
7981 case glslang::EbtUint16:
7982 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7983 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007984 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007985 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007986 break;
7987 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007988 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007989 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007990 case glslang::EbtInt64:
7991 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7992 break;
7993 case glslang::EbtUint64:
7994 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7995 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007996 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007997 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007998 break;
7999 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008000 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008001 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008002 case glslang::EbtFloat16:
8003 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8004 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008005 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07008006 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008007 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008008 case glslang::EbtReference:
8009 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8010 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8011 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008012 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008013 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008014 break;
8015 }
8016 ++nextConst;
8017 return scalar;
8018 }
8019
8020 return builder.makeCompositeConstant(typeId, spvConsts);
8021}
8022
John Kessenich7c1aa102015-10-15 13:29:11 -06008023// Return true if the node is a constant or symbol whose reading has no
8024// non-trivial observable cost or effect.
8025bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8026{
8027 // don't know what this is
8028 if (node == nullptr)
8029 return false;
8030
8031 // a constant is safe
8032 if (node->getAsConstantUnion() != nullptr)
8033 return true;
8034
8035 // not a symbol means non-trivial
8036 if (node->getAsSymbolNode() == nullptr)
8037 return false;
8038
8039 // a symbol, depends on what's being read
8040 switch (node->getType().getQualifier().storage) {
8041 case glslang::EvqTemporary:
8042 case glslang::EvqGlobal:
8043 case glslang::EvqIn:
8044 case glslang::EvqInOut:
8045 case glslang::EvqConst:
8046 case glslang::EvqConstReadOnly:
8047 case glslang::EvqUniform:
8048 return true;
8049 default:
8050 return false;
8051 }
qining25262b32016-05-06 17:25:16 -04008052}
John Kessenich7c1aa102015-10-15 13:29:11 -06008053
8054// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008055// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008056// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008057// Return true if trivial.
8058bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8059{
8060 if (node == nullptr)
8061 return false;
8062
John Kessenich84cc15f2017-05-24 16:44:47 -06008063 // count non scalars as trivial, as well as anything coming from HLSL
8064 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008065 return true;
8066
John Kessenich7c1aa102015-10-15 13:29:11 -06008067 // symbols and constants are trivial
8068 if (isTrivialLeaf(node))
8069 return true;
8070
8071 // otherwise, it needs to be a simple operation or one or two leaf nodes
8072
8073 // not a simple operation
8074 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8075 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8076 if (binaryNode == nullptr && unaryNode == nullptr)
8077 return false;
8078
8079 // not on leaf nodes
8080 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8081 return false;
8082
8083 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8084 return false;
8085 }
8086
8087 switch (node->getAsOperator()->getOp()) {
8088 case glslang::EOpLogicalNot:
8089 case glslang::EOpConvIntToBool:
8090 case glslang::EOpConvUintToBool:
8091 case glslang::EOpConvFloatToBool:
8092 case glslang::EOpConvDoubleToBool:
8093 case glslang::EOpEqual:
8094 case glslang::EOpNotEqual:
8095 case glslang::EOpLessThan:
8096 case glslang::EOpGreaterThan:
8097 case glslang::EOpLessThanEqual:
8098 case glslang::EOpGreaterThanEqual:
8099 case glslang::EOpIndexDirect:
8100 case glslang::EOpIndexDirectStruct:
8101 case glslang::EOpLogicalXor:
8102 case glslang::EOpAny:
8103 case glslang::EOpAll:
8104 return true;
8105 default:
8106 return false;
8107 }
8108}
8109
8110// Emit short-circuiting code, where 'right' is never evaluated unless
8111// the left side is true (for &&) or false (for ||).
8112spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8113{
8114 spv::Id boolTypeId = builder.makeBoolType();
8115
8116 // emit left operand
8117 builder.clearAccessChain();
8118 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008119 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008120
8121 // Operands to accumulate OpPhi operands
8122 std::vector<spv::Id> phiOperands;
8123 // accumulate left operand's phi information
8124 phiOperands.push_back(leftId);
8125 phiOperands.push_back(builder.getBuildPoint()->getId());
8126
8127 // Make the two kinds of operation symmetric with a "!"
8128 // || => emit "if (! left) result = right"
8129 // && => emit "if ( left) result = right"
8130 //
8131 // TODO: this runtime "not" for || could be avoided by adding functionality
8132 // to 'builder' to have an "else" without an "then"
8133 if (op == glslang::EOpLogicalOr)
8134 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8135
8136 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008137 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008138
8139 // emit right operand as the "then" part of the "if"
8140 builder.clearAccessChain();
8141 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008142 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008143
8144 // accumulate left operand's phi information
8145 phiOperands.push_back(rightId);
8146 phiOperands.push_back(builder.getBuildPoint()->getId());
8147
8148 // finish the "if"
8149 ifBuilder.makeEndIf();
8150
8151 // phi together the two results
8152 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8153}
8154
Frank Henigman541f7bb2018-01-16 00:18:26 -05008155#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008156// Return type Id of the imported set of extended instructions corresponds to the name.
8157// Import this set if it has not been imported yet.
8158spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8159{
8160 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8161 return extBuiltinMap[name];
8162 else {
Rex Xu51596642016-09-21 18:56:12 +08008163 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008164 spv::Id extBuiltins = builder.import(name);
8165 extBuiltinMap[name] = extBuiltins;
8166 return extBuiltins;
8167 }
8168}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008169#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008170
John Kessenich140f3df2015-06-26 16:58:36 -06008171}; // end anonymous namespace
8172
8173namespace glslang {
8174
John Kessenich68d78fd2015-07-12 19:28:10 -06008175void GetSpirvVersion(std::string& version)
8176{
John Kessenich9e55f632015-07-15 10:03:39 -06008177 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008178 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008179 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008180 version = buf;
8181}
8182
John Kessenicha372a3e2017-11-02 22:32:14 -06008183// For low-order part of the generator's magic number. Bump up
8184// when there is a change in the style (e.g., if SSA form changes,
8185// or a different instruction sequence to do something gets used).
8186int GetSpirvGeneratorVersion()
8187{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008188 // return 1; // start
8189 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008190 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008191 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008192 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008193 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8194 // versions 4 and 6 each generate OpArrayLength as it has long been done
8195 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008196}
8197
John Kessenich140f3df2015-06-26 16:58:36 -06008198// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008199void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008200{
8201 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008202 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008203 if (out.fail())
8204 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008205 for (int i = 0; i < (int)spirv.size(); ++i) {
8206 unsigned int word = spirv[i];
8207 out.write((const char*)&word, 4);
8208 }
8209 out.close();
8210}
8211
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008212// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008213void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008214{
8215 std::ofstream out;
8216 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008217 if (out.fail())
8218 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008219 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008220 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008221 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008222 if (varName != nullptr) {
8223 out << "\t #pragma once" << std::endl;
8224 out << "const uint32_t " << varName << "[] = {" << std::endl;
8225 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008226 const int WORDS_PER_LINE = 8;
8227 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8228 out << "\t";
8229 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8230 const unsigned int word = spirv[i + j];
8231 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8232 if (i + j + 1 < (int)spirv.size()) {
8233 out << ",";
8234 }
8235 }
8236 out << std::endl;
8237 }
Flavio15017db2017-02-15 14:29:33 -08008238 if (varName != nullptr) {
8239 out << "};";
8240 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008241 out.close();
8242}
8243
John Kessenich140f3df2015-06-26 16:58:36 -06008244//
8245// Set up the glslang traversal
8246//
John Kessenich4e11b612018-08-30 16:56:59 -06008247void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008248{
Lei Zhang17535f72016-05-04 15:55:59 -04008249 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008250 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008251}
8252
John Kessenich4e11b612018-08-30 16:56:59 -06008253void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008254 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008255{
John Kessenich140f3df2015-06-26 16:58:36 -06008256 TIntermNode* root = intermediate.getTreeRoot();
8257
8258 if (root == 0)
8259 return;
8260
John Kessenich4e11b612018-08-30 16:56:59 -06008261 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008262 if (options == nullptr)
8263 options = &defaultOptions;
8264
John Kessenich4e11b612018-08-30 16:56:59 -06008265 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008266
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008267 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008268 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008269 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008270 it.dumpSpv(spirv);
8271
GregFfb03a552018-03-29 11:49:14 -06008272#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008273 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8274 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008275 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8276 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008277 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008278 prelegalization = false;
8279 }
John Kessenich717c80a2018-08-23 15:17:10 -06008280
John Kessenich4e11b612018-08-30 16:56:59 -06008281 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008282 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008283
John Kessenich717c80a2018-08-23 15:17:10 -06008284 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008285 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008286
GregFcd1f1692017-09-21 18:40:22 -06008287#endif
8288
John Kessenich4e11b612018-08-30 16:56:59 -06008289 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008290}
8291
8292}; // end namespace glslang