blob: 9ad19b54c0457f242053a90934e8f906df0fc4e8 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
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 Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
Daniel Koch593a4e02019-05-27 16:46:31 -0400891 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400920
921 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700922 case glslang::EbvBaryCoordNV:
923 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
924 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
925 return spv::BuiltInBaryCoordNV;
926 case glslang::EbvBaryCoordNoPerspNV:
927 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
928 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
929 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400930
931 // mesh shaders
932 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400949
950 // sm builtins
951 case glslang::EbvWarpsPerSM:
952 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
953 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
954 return spv::BuiltInWarpsPerSMNV;
955 case glslang::EbvSMCount:
956 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
957 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
958 return spv::BuiltInSMCountNV;
959 case glslang::EbvWarpID:
960 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
961 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
962 return spv::BuiltInWarpIDNV;
963 case glslang::EbvSMID:
964 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
965 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
966 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800967 default:
968 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600969 }
970}
971
Rex Xufc618912015-09-09 16:42:49 +0800972// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700973spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800974{
975 assert(type.getBasicType() == glslang::EbtSampler);
976
John Kessenich5d0fa972016-02-15 11:57:00 -0700977 // Check for capabilities
978 switch (type.getQualifier().layoutFormat) {
979 case glslang::ElfRg32f:
980 case glslang::ElfRg16f:
981 case glslang::ElfR11fG11fB10f:
982 case glslang::ElfR16f:
983 case glslang::ElfRgba16:
984 case glslang::ElfRgb10A2:
985 case glslang::ElfRg16:
986 case glslang::ElfRg8:
987 case glslang::ElfR16:
988 case glslang::ElfR8:
989 case glslang::ElfRgba16Snorm:
990 case glslang::ElfRg16Snorm:
991 case glslang::ElfRg8Snorm:
992 case glslang::ElfR16Snorm:
993 case glslang::ElfR8Snorm:
994
995 case glslang::ElfRg32i:
996 case glslang::ElfRg16i:
997 case glslang::ElfRg8i:
998 case glslang::ElfR16i:
999 case glslang::ElfR8i:
1000
1001 case glslang::ElfRgb10a2ui:
1002 case glslang::ElfRg32ui:
1003 case glslang::ElfRg16ui:
1004 case glslang::ElfRg8ui:
1005 case glslang::ElfR16ui:
1006 case glslang::ElfR8ui:
1007 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1008 break;
1009
1010 default:
1011 break;
1012 }
1013
1014 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001015 switch (type.getQualifier().layoutFormat) {
1016 case glslang::ElfNone: return spv::ImageFormatUnknown;
1017 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1018 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1019 case glslang::ElfR32f: return spv::ImageFormatR32f;
1020 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1021 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1022 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1023 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1024 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1025 case glslang::ElfR16f: return spv::ImageFormatR16f;
1026 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1027 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1028 case glslang::ElfRg16: return spv::ImageFormatRg16;
1029 case glslang::ElfRg8: return spv::ImageFormatRg8;
1030 case glslang::ElfR16: return spv::ImageFormatR16;
1031 case glslang::ElfR8: return spv::ImageFormatR8;
1032 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1033 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1034 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1035 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1036 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1037 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1038 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1039 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1040 case glslang::ElfR32i: return spv::ImageFormatR32i;
1041 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1042 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1043 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1044 case glslang::ElfR16i: return spv::ImageFormatR16i;
1045 case glslang::ElfR8i: return spv::ImageFormatR8i;
1046 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1047 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1048 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1049 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1050 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1051 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1052 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1053 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1054 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1055 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001056 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001057 }
1058}
1059
John Kesseniche18fd202018-01-30 11:01:39 -07001060spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001061{
John Kesseniche18fd202018-01-30 11:01:39 -07001062 if (selectionNode.getFlatten())
1063 return spv::SelectionControlFlattenMask;
1064 if (selectionNode.getDontFlatten())
1065 return spv::SelectionControlDontFlattenMask;
1066 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001067}
1068
John Kesseniche18fd202018-01-30 11:01:39 -07001069spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001070{
John Kesseniche18fd202018-01-30 11:01:39 -07001071 if (switchNode.getFlatten())
1072 return spv::SelectionControlFlattenMask;
1073 if (switchNode.getDontFlatten())
1074 return spv::SelectionControlDontFlattenMask;
1075 return spv::SelectionControlMaskNone;
1076}
1077
John Kessenicha2858d92018-01-31 08:11:18 -07001078// return a non-0 dependency if the dependency argument must be set
1079spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001080 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001081{
1082 spv::LoopControlMask control = spv::LoopControlMaskNone;
1083
1084 if (loopNode.getDontUnroll())
1085 control = control | spv::LoopControlDontUnrollMask;
1086 if (loopNode.getUnroll())
1087 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001088 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001089 control = control | spv::LoopControlDependencyInfiniteMask;
1090 else if (loopNode.getLoopDependency() > 0) {
1091 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001092 operands.push_back((unsigned int)loopNode.getLoopDependency());
1093 }
1094 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1095 if (loopNode.getMinIterations() > 0) {
1096 control = control | spv::LoopControlMinIterationsMask;
1097 operands.push_back(loopNode.getMinIterations());
1098 }
1099 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1100 control = control | spv::LoopControlMaxIterationsMask;
1101 operands.push_back(loopNode.getMaxIterations());
1102 }
1103 if (loopNode.getIterationMultiple() > 1) {
1104 control = control | spv::LoopControlIterationMultipleMask;
1105 operands.push_back(loopNode.getIterationMultiple());
1106 }
1107 if (loopNode.getPeelCount() > 0) {
1108 control = control | spv::LoopControlPeelCountMask;
1109 operands.push_back(loopNode.getPeelCount());
1110 }
1111 if (loopNode.getPartialCount() > 0) {
1112 control = control | spv::LoopControlPartialCountMask;
1113 operands.push_back(loopNode.getPartialCount());
1114 }
John Kessenicha2858d92018-01-31 08:11:18 -07001115 }
John Kesseniche18fd202018-01-30 11:01:39 -07001116
1117 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001118}
1119
John Kessenicha5c5fb62017-05-05 05:09:58 -06001120// Translate glslang type to SPIR-V storage class.
1121spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1122{
1123 if (type.getQualifier().isPipeInput())
1124 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001125 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001126 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001127
1128 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1129 type.getQualifier().storage == glslang::EvqUniform) {
1130 if (type.getBasicType() == glslang::EbtAtomicUint)
1131 return spv::StorageClassAtomicCounter;
1132 if (type.containsOpaque())
1133 return spv::StorageClassUniformConstant;
1134 }
1135
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001136#ifdef NV_EXTENSIONS
1137 if (type.getQualifier().isUniformOrBuffer() &&
1138 type.getQualifier().layoutShaderRecordNV) {
1139 return spv::StorageClassShaderRecordBufferNV;
1140 }
1141#endif
1142
John Kessenichbed4e4f2017-09-08 02:38:07 -06001143 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001144 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001145 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 }
1147
1148 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001149 if (type.getQualifier().layoutPushConstant)
1150 return spv::StorageClassPushConstant;
1151 if (type.getBasicType() == glslang::EbtBlock)
1152 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001153 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001155
1156 switch (type.getQualifier().storage) {
1157 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1158 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1159 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1160 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001161#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001162 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1163 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1164 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1165 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1166 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001167#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001168 default:
1169 assert(0);
1170 break;
1171 }
1172
1173 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001174}
1175
John Kessenich5611c6d2018-04-05 11:25:02 -06001176// Add capabilities pertaining to how an array is indexed.
1177void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1178 const glslang::TType& indexType)
1179{
1180 if (indexType.getQualifier().isNonUniform()) {
1181 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001182 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 if (baseType.getBasicType() == glslang::EbtSampler) {
1184 if (baseType.getQualifier().hasAttachment())
1185 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1186 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1187 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1188 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1190 else if (baseType.isImage())
1191 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1192 else if (baseType.isTexture())
1193 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1194 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1195 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1196 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1197 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1198 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1199 }
1200 } else {
1201 // assume a dynamically uniform index
1202 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001203 if (baseType.getQualifier().hasAttachment()) {
1204 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001205 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001206 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1207 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001208 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001209 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1210 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001211 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001213 }
1214 }
1215}
1216
qining25262b32016-05-06 17:25:16 -04001217// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001218// descriptor set.
1219bool IsDescriptorResource(const glslang::TType& type)
1220{
John Kessenichf7497e22016-03-08 21:36:22 -07001221 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001222 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001223 return type.getQualifier().isUniformOrBuffer() &&
1224#ifdef NV_EXTENSIONS
1225 ! type.getQualifier().layoutShaderRecordNV &&
1226#endif
1227 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001228
1229 // non block...
1230 // basically samplerXXX/subpass/sampler/texture are all included
1231 // if they are the global-scope-class, not the function parameter
1232 // (or local, if they ever exist) class.
1233 if (type.getBasicType() == glslang::EbtSampler)
1234 return type.getQualifier().isUniformOrBuffer();
1235
1236 // None of the above.
1237 return false;
1238}
1239
John Kesseniche0b6cad2015-12-24 10:30:13 -07001240void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1241{
1242 if (child.layoutMatrix == glslang::ElmNone)
1243 child.layoutMatrix = parent.layoutMatrix;
1244
1245 if (parent.invariant)
1246 child.invariant = true;
1247 if (parent.nopersp)
1248 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001249#ifdef AMD_EXTENSIONS
1250 if (parent.explicitInterp)
1251 child.explicitInterp = true;
1252#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001253 if (parent.flat)
1254 child.flat = true;
1255 if (parent.centroid)
1256 child.centroid = true;
1257 if (parent.patch)
1258 child.patch = true;
1259 if (parent.sample)
1260 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001261 if (parent.coherent)
1262 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001263 if (parent.devicecoherent)
1264 child.devicecoherent = true;
1265 if (parent.queuefamilycoherent)
1266 child.queuefamilycoherent = true;
1267 if (parent.workgroupcoherent)
1268 child.workgroupcoherent = true;
1269 if (parent.subgroupcoherent)
1270 child.subgroupcoherent = true;
1271 if (parent.nonprivate)
1272 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001273 if (parent.volatil)
1274 child.volatil = true;
1275 if (parent.restrict)
1276 child.restrict = true;
1277 if (parent.readonly)
1278 child.readonly = true;
1279 if (parent.writeonly)
1280 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001281#ifdef NV_EXTENSIONS
1282 if (parent.perPrimitiveNV)
1283 child.perPrimitiveNV = true;
1284 if (parent.perViewNV)
1285 child.perViewNV = true;
1286 if (parent.perTaskNV)
1287 child.perTaskNV = true;
1288#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001289}
1290
John Kessenichf2b7f332016-09-01 17:05:23 -06001291bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001292{
John Kessenich7b9fa252016-01-21 18:56:57 -07001293 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001294 // - struct members might inherit from a struct declaration
1295 // (note that non-block structs don't explicitly inherit,
1296 // only implicitly, meaning no decoration involved)
1297 // - affect decorations on the struct members
1298 // (note smooth does not, and expecting something like volatile
1299 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001300 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001301 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302}
1303
John Kessenich140f3df2015-06-26 16:58:36 -06001304//
1305// Implement the TGlslangToSpvTraverser class.
1306//
1307
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001308TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001309 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1310 : TIntermTraverser(true, false, true),
1311 options(options),
1312 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001313 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001314 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001315 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001316 glslangIntermediate(glslangIntermediate)
1317{
1318 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1319
1320 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001321 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1322 glslangIntermediate->getVersion());
1323
John Kessenich121853f2017-05-31 17:11:16 -06001324 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001325 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001326 builder.setSourceFile(glslangIntermediate->getSourceFile());
1327
1328 // Set the source shader's text. If for SPV version 1.0, include
1329 // a preamble in comments stating the OpModuleProcessed instructions.
1330 // Otherwise, emit those as actual instructions.
1331 std::string text;
1332 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1333 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001334 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001335 text.append("// OpModuleProcessed ");
1336 text.append(processes[p]);
1337 text.append("\n");
1338 } else
1339 builder.addModuleProcessed(processes[p]);
1340 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001341 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001342 text.append("#line 1\n");
1343 text.append(glslangIntermediate->getSourceText());
1344 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001345 // Pass name and text for all included files
1346 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1347 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1348 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001349 }
John Kessenich140f3df2015-06-26 16:58:36 -06001350 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001351
1352 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1353 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1354
1355 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1356 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1357 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1358 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1359 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001360 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001361 memoryModel = spv::MemoryModelVulkanKHR;
1362 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001363 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001364 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001365 builder.setMemoryModel(addressingModel, memoryModel);
1366
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001367 if (glslangIntermediate->usingVariablePointers()) {
1368 builder.addCapability(spv::CapabilityVariablePointers);
1369 }
1370
John Kessenicheee9d532016-09-19 18:09:30 -06001371 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1372 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001375 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1376 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.addSourceExtension(it->c_str());
1378
1379 // Add the top-level modes for this shader.
1380
John Kessenich92187592016-02-01 13:45:25 -07001381 if (glslangIntermediate->getXfbMode()) {
1382 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001384 }
John Kessenich140f3df2015-06-26 16:58:36 -06001385
1386 unsigned int mode;
1387 switch (glslangIntermediate->getStage()) {
1388 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001389 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001390 break;
1391
steve-lunarge7412492017-03-23 11:56:07 -06001392 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001393 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001394 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001395
steve-lunarge7412492017-03-23 11:56:07 -06001396 glslang::TLayoutGeometry primitive;
1397
1398 if (glslangIntermediate->getStage() == EShLangTessControl) {
1399 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1400 primitive = glslangIntermediate->getOutputPrimitive();
1401 } else {
1402 primitive = glslangIntermediate->getInputPrimitive();
1403 }
1404
1405 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001406 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1407 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1408 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001409 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001410 }
John Kessenich4016e382016-07-15 11:53:56 -06001411 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1413
John Kesseniche6903322015-10-13 16:29:02 -06001414 switch (glslangIntermediate->getVertexSpacing()) {
1415 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1416 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1417 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001418 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001419 }
John Kessenich4016e382016-07-15 11:53:56 -06001420 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001421 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1422
1423 switch (glslangIntermediate->getVertexOrder()) {
1424 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1425 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001426 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001427 }
John Kessenich4016e382016-07-15 11:53:56 -06001428 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001429 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1430
1431 if (glslangIntermediate->getPointMode())
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 break;
1434
1435 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001436 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001437 switch (glslangIntermediate->getInputPrimitive()) {
1438 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1439 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1440 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001441 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001442 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001443 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001444 }
John Kessenich4016e382016-07-15 11:53:56 -06001445 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001446 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001447
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1449
1450 switch (glslangIntermediate->getOutputPrimitive()) {
1451 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1452 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1453 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001454 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 }
John Kessenich4016e382016-07-15 11:53:56 -06001456 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1459 break;
1460
1461 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001462 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001463 if (glslangIntermediate->getPixelCenterInteger())
1464 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001465
John Kessenich140f3df2015-06-26 16:58:36 -06001466 if (glslangIntermediate->getOriginUpperLeft())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001468 else
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001470
1471 if (glslangIntermediate->getEarlyFragmentTests())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1473
chaocc1204522017-06-30 17:14:30 -07001474 if (glslangIntermediate->getPostDepthCoverage()) {
1475 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1477 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1478 }
1479
John Kesseniche6903322015-10-13 16:29:02 -06001480 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001481 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1482 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001483 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001484 }
John Kessenich4016e382016-07-15 11:53:56 -06001485 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001486 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1487
1488 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001490
1491 switch (glslangIntermediate->getInterlockOrdering()) {
1492 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1493 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1494 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1495 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1496 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1497 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1498 default: mode = spv::ExecutionModeMax; break;
1499 }
1500 if (mode != spv::ExecutionModeMax) {
1501 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1502 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1503 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1504 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1505 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1506 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1507 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1508 } else {
1509 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1510 }
1511 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1512 }
1513
John Kessenich140f3df2015-06-26 16:58:36 -06001514 break;
1515
1516 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001517 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1519 glslangIntermediate->getLocalSize(1),
1520 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001521#ifdef NV_EXTENSIONS
1522 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1523 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1524 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1525 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1526 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1527 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1529 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1530 }
1531#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001532 break;
1533
Chao Chen3c366992018-09-19 11:41:59 -07001534#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001535 case EShLangRayGenNV:
1536 case EShLangIntersectNV:
1537 case EShLangAnyHitNV:
1538 case EShLangClosestHitNV:
1539 case EShLangMissNV:
1540 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001541 builder.addCapability(spv::CapabilityRayTracingNV);
1542 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001543 break;
Chao Chen3c366992018-09-19 11:41:59 -07001544 case EShLangTaskNV:
1545 case EShLangMeshNV:
1546 builder.addCapability(spv::CapabilityMeshShadingNV);
1547 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1549 glslangIntermediate->getLocalSize(1),
1550 glslangIntermediate->getLocalSize(2));
1551 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1552 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1554
1555 switch (glslangIntermediate->getOutputPrimitive()) {
1556 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1557 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1558 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1559 default: mode = spv::ExecutionModeMax; break;
1560 }
1561 if (mode != spv::ExecutionModeMax)
1562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563 }
1564 break;
1565#endif
1566
John Kessenich140f3df2015-06-26 16:58:36 -06001567 default:
1568 break;
1569 }
John Kessenich140f3df2015-06-26 16:58:36 -06001570}
1571
John Kessenichfca82622016-11-26 13:23:20 -07001572// Finish creating SPV, after the traversal is complete.
1573void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001574{
John Kessenichf04c51b2018-08-03 15:56:12 -06001575 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001576 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001577 builder.setBuildPoint(shaderEntry->getLastBlock());
1578 builder.leaveFunction();
1579 }
1580
John Kessenich7ba63412015-12-20 17:37:07 -07001581 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001582 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1583 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001584
John Kessenichf04c51b2018-08-03 15:56:12 -06001585 // Add capabilities, extensions, remove unneeded decorations, etc.,
1586 // based on the resulting SPIR-V.
1587 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001588}
1589
John Kessenichfca82622016-11-26 13:23:20 -07001590// Write the SPV into 'out'.
1591void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001592{
John Kessenichfca82622016-11-26 13:23:20 -07001593 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001594}
1595
1596//
1597// Implement the traversal functions.
1598//
1599// Return true from interior nodes to have the external traversal
1600// continue on to children. Return false if children were
1601// already processed.
1602//
1603
1604//
qining25262b32016-05-06 17:25:16 -04001605// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001606// - uniform/input reads
1607// - output writes
1608// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1609// - something simple that degenerates into the last bullet
1610//
1611void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1612{
qining75d1d802016-04-06 14:42:01 -04001613 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1614 if (symbol->getType().getQualifier().isSpecConstant())
1615 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1616
John Kessenich140f3df2015-06-26 16:58:36 -06001617 // getSymbolId() will set up all the IO decorations on the first call.
1618 // Formal function parameters were mapped during makeFunctions().
1619 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001620
1621 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1622 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001623 // Consider adding to the OpEntryPoint interface list.
1624 // Only looking at structures if they have at least one member.
1625 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1626 spv::StorageClass sc = builder.getStorageClass(id);
1627 // Before SPIR-V 1.4, we only want to include Input and Output.
1628 // Starting with SPIR-V 1.4, we want all globals.
1629 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1630 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001631 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001632 }
John Kessenich5f77d862017-09-19 11:09:59 -06001633 }
John Kessenich7ba63412015-12-20 17:37:07 -07001634 }
1635
1636 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001637 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001638 // Prepare to generate code for the access
1639
1640 // L-value chains will be computed left to right. We're on the symbol now,
1641 // which is the left-most part of the access chain, so now is "clear" time,
1642 // followed by setting the base.
1643 builder.clearAccessChain();
1644
1645 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001646 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001647 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001648 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001649 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001650 // These are also pure R-values.
1651 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001652 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001653 builder.setAccessChainRValue(id);
1654 else
1655 builder.setAccessChainLValue(id);
1656 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001657
1658 // Process linkage-only nodes for any special additional interface work.
1659 if (linkageOnly) {
1660 if (glslangIntermediate->getHlslFunctionality1()) {
1661 // Map implicit counter buffers to their originating buffers, which should have been
1662 // seen by now, given earlier pruning of unused counters, and preservation of order
1663 // of declaration.
1664 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1665 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1666 // Save possible originating buffers for counter buffers, keyed by
1667 // making the potential counter-buffer name.
1668 std::string keyName = symbol->getName().c_str();
1669 keyName = glslangIntermediate->addCounterBufferName(keyName);
1670 counterOriginator[keyName] = symbol;
1671 } else {
1672 // Handle a counter buffer, by finding the saved originating buffer.
1673 std::string keyName = symbol->getName().c_str();
1674 auto it = counterOriginator.find(keyName);
1675 if (it != counterOriginator.end()) {
1676 id = getSymbolId(it->second);
1677 if (id != spv::NoResult) {
1678 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001679 if (counterId != spv::NoResult) {
1680 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001681 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001682 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001683 }
1684 }
1685 }
1686 }
1687 }
1688 }
John Kessenich140f3df2015-06-26 16:58:36 -06001689}
1690
1691bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1692{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001693 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001694
qining40887662016-04-03 22:20:42 -04001695 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1696 if (node->getType().getQualifier().isSpecConstant())
1697 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1698
John Kessenich140f3df2015-06-26 16:58:36 -06001699 // First, handle special cases
1700 switch (node->getOp()) {
1701 case glslang::EOpAssign:
1702 case glslang::EOpAddAssign:
1703 case glslang::EOpSubAssign:
1704 case glslang::EOpMulAssign:
1705 case glslang::EOpVectorTimesMatrixAssign:
1706 case glslang::EOpVectorTimesScalarAssign:
1707 case glslang::EOpMatrixTimesScalarAssign:
1708 case glslang::EOpMatrixTimesMatrixAssign:
1709 case glslang::EOpDivAssign:
1710 case glslang::EOpModAssign:
1711 case glslang::EOpAndAssign:
1712 case glslang::EOpInclusiveOrAssign:
1713 case glslang::EOpExclusiveOrAssign:
1714 case glslang::EOpLeftShiftAssign:
1715 case glslang::EOpRightShiftAssign:
1716 // A bin-op assign "a += b" means the same thing as "a = a + b"
1717 // where a is evaluated before b. For a simple assignment, GLSL
1718 // says to evaluate the left before the right. So, always, left
1719 // node then right node.
1720 {
1721 // get the left l-value, save it away
1722 builder.clearAccessChain();
1723 node->getLeft()->traverse(this);
1724 spv::Builder::AccessChain lValue = builder.getAccessChain();
1725
1726 // evaluate the right
1727 builder.clearAccessChain();
1728 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001729 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001730
1731 if (node->getOp() != glslang::EOpAssign) {
1732 // the left is also an r-value
1733 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001734 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001735
1736 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001737 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001738 TranslateNoContractionDecoration(node->getType().getQualifier()),
1739 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001740 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001741 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1742 node->getType().getBasicType());
1743
1744 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001745 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001746 }
1747
1748 // store the result
1749 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001750 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001751
1752 // assignments are expressions having an rValue after they are evaluated...
1753 builder.clearAccessChain();
1754 builder.setAccessChainRValue(rValue);
1755 }
1756 return false;
1757 case glslang::EOpIndexDirect:
1758 case glslang::EOpIndexDirectStruct:
1759 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001760 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001761 // Get the left part of the access chain.
1762 node->getLeft()->traverse(this);
1763
1764 // Add the next element in the chain
1765
David Netoa901ffe2016-06-08 14:11:40 +01001766 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001767 if (! node->getLeft()->getType().isArray() &&
1768 node->getLeft()->getType().isVector() &&
1769 node->getOp() == glslang::EOpIndexDirect) {
1770 // This is essentially a hard-coded vector swizzle of size 1,
1771 // so short circuit the access-chain stuff with a swizzle.
1772 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001773 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001774 int dummySize;
1775 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1776 TranslateCoherent(node->getLeft()->getType()),
1777 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001778 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001779
1780 // Load through a block reference is performed with a dot operator that
1781 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1782 // do a load and reset the access chain.
1783 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1784 !node->getLeft()->getType().isArray() &&
1785 node->getOp() == glslang::EOpIndexDirectStruct)
1786 {
1787 spv::Id left = accessChainLoad(node->getLeft()->getType());
1788 builder.clearAccessChain();
1789 builder.setAccessChainLValue(left);
1790 }
1791
David Netoa901ffe2016-06-08 14:11:40 +01001792 int spvIndex = glslangIndex;
1793 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1794 node->getOp() == glslang::EOpIndexDirectStruct)
1795 {
1796 // This may be, e.g., an anonymous block-member selection, which generally need
1797 // index remapping due to hidden members in anonymous blocks.
1798 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1799 assert(remapper.size() > 0);
1800 spvIndex = remapper[glslangIndex];
1801 }
John Kessenichebb50532016-05-16 19:22:05 -06001802
David Netoa901ffe2016-06-08 14:11:40 +01001803 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001804 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001805
1806 // Add capabilities here for accessing PointSize and clip/cull distance.
1807 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001808 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001809 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001810 }
1811 }
1812 return false;
1813 case glslang::EOpIndexIndirect:
1814 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001815 // Array, matrix, or vector indirection with variable index.
1816 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001817 // matrices are arrays of vectors, so will also work for a matrix.
1818 // Will use the access chain's 'component' for variable index into a vector.
1819
1820 // This adapter is building access chains left to right.
1821 // Set up the access chain to the left.
1822 node->getLeft()->traverse(this);
1823
1824 // save it so that computing the right side doesn't trash it
1825 spv::Builder::AccessChain partial = builder.getAccessChain();
1826
1827 // compute the next index in the chain
1828 builder.clearAccessChain();
1829 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001830 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001831
John Kessenich5611c6d2018-04-05 11:25:02 -06001832 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1833
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // restore the saved access chain
1835 builder.setAccessChain(partial);
1836
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001837 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1838 int dummySize;
1839 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1840 TranslateCoherent(node->getLeft()->getType()),
1841 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1842 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001843 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001844 }
1845 return false;
1846 case glslang::EOpVectorSwizzle:
1847 {
1848 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001849 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001850 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001851 int dummySize;
1852 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1853 TranslateCoherent(node->getLeft()->getType()),
1854 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001855 }
1856 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001857 case glslang::EOpMatrixSwizzle:
1858 logger->missingFunctionality("matrix swizzle");
1859 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001860 case glslang::EOpLogicalOr:
1861 case glslang::EOpLogicalAnd:
1862 {
1863
1864 // These may require short circuiting, but can sometimes be done as straight
1865 // binary operations. The right operand must be short circuited if it has
1866 // side effects, and should probably be if it is complex.
1867 if (isTrivial(node->getRight()->getAsTyped()))
1868 break; // handle below as a normal binary operation
1869 // otherwise, we need to do dynamic short circuiting on the right operand
1870 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1871 builder.clearAccessChain();
1872 builder.setAccessChainRValue(result);
1873 }
1874 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001875 default:
1876 break;
1877 }
1878
1879 // Assume generic binary op...
1880
John Kessenich32cfd492016-02-02 12:37:46 -07001881 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001882 builder.clearAccessChain();
1883 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001885
John Kessenich32cfd492016-02-02 12:37:46 -07001886 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001887 builder.clearAccessChain();
1888 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
John Kessenich32cfd492016-02-02 12:37:46 -07001891 // get result
John Kessenichead86222018-03-28 18:01:20 -06001892 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001893 TranslateNoContractionDecoration(node->getType().getQualifier()),
1894 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001895 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001896 convertGlslangToSpvType(node->getType()), left, right,
1897 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001898
John Kessenich50e57562015-12-21 21:21:11 -07001899 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001900 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001901 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001902 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001903 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001904 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001905 return false;
1906 }
John Kessenich140f3df2015-06-26 16:58:36 -06001907}
1908
1909bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1910{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001911 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001912
qining40887662016-04-03 22:20:42 -04001913 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1914 if (node->getType().getQualifier().isSpecConstant())
1915 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1916
John Kessenichfc51d282015-08-19 13:34:18 -06001917 spv::Id result = spv::NoResult;
1918
1919 // try texturing first
1920 result = createImageTextureFunctionCall(node);
1921 if (result != spv::NoResult) {
1922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(result);
1924
1925 return false; // done with this node
1926 }
1927
1928 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001929
1930 if (node->getOp() == glslang::EOpArrayLength) {
1931 // Quite special; won't want to evaluate the operand.
1932
John Kessenich5611c6d2018-04-05 11:25:02 -06001933 // Currently, the front-end does not allow .length() on an array until it is sized,
1934 // except for the last block membeor of an SSBO.
1935 // TODO: If this changes, link-time sized arrays might show up here, and need their
1936 // size extracted.
1937
John Kessenichc9a80832015-09-12 12:17:44 -06001938 // Normal .length() would have been constant folded by the front-end.
1939 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001940 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001941
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001942 spv::Id length;
1943 if (node->getOperand()->getType().isCoopMat()) {
1944 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1945
1946 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1947 assert(builder.isCooperativeMatrixType(typeId));
1948
1949 length = builder.createCooperativeMatrixLength(typeId);
1950 } else {
1951 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1952 block->traverse(this);
1953 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1954 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1955 }
John Kessenichc9a80832015-09-12 12:17:44 -06001956
John Kessenich8c869672018-11-28 07:01:37 -07001957 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1958 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1959 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001960 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1961 if (builder.isInSpecConstCodeGenMode()) {
1962 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1963 } else {
1964 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1965 }
1966 }
John Kessenich8c869672018-11-28 07:01:37 -07001967
John Kessenichc9a80832015-09-12 12:17:44 -06001968 builder.clearAccessChain();
1969 builder.setAccessChainRValue(length);
1970
1971 return false;
1972 }
1973
John Kessenichfc51d282015-08-19 13:34:18 -06001974 // Start by evaluating the operand
1975
John Kessenich8c8505c2016-07-26 12:50:38 -06001976 // Does it need a swizzle inversion? If so, evaluation is inverted;
1977 // operate first on the swizzle base, then apply the swizzle.
1978 spv::Id invertedType = spv::NoType;
1979 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1980 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1981 invertedType = getInvertedSwizzleType(*node->getOperand());
1982
John Kessenich140f3df2015-06-26 16:58:36 -06001983 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001984 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06001985 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001986 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06001987 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001988 operandNode = node->getOperand();
1989
1990 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001991
Rex Xufc618912015-09-09 16:42:49 +08001992 spv::Id operand = spv::NoResult;
1993
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001994 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
1995
Rex Xufc618912015-09-09 16:42:49 +08001996 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1997 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001998 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05001999 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002000 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002001 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2002 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2003 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002004 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002005
John Kessenichead86222018-03-28 18:01:20 -06002006 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002007 TranslateNoContractionDecoration(node->getType().getQualifier()),
2008 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002009
2010 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002011 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002012 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002013
2014 // if not, then possibly an operation
2015 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002016 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002017
2018 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002019 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002020 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002021 builder.addDecoration(result, decorations.nonUniform);
2022 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002023
John Kessenich140f3df2015-06-26 16:58:36 -06002024 builder.clearAccessChain();
2025 builder.setAccessChainRValue(result);
2026
2027 return false; // done with this node
2028 }
2029
2030 // it must be a special case, check...
2031 switch (node->getOp()) {
2032 case glslang::EOpPostIncrement:
2033 case glslang::EOpPostDecrement:
2034 case glslang::EOpPreIncrement:
2035 case glslang::EOpPreDecrement:
2036 {
2037 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002038 spv::Id one = 0;
2039 if (node->getBasicType() == glslang::EbtFloat)
2040 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002041 else if (node->getBasicType() == glslang::EbtDouble)
2042 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002043 else if (node->getBasicType() == glslang::EbtFloat16)
2044 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002045 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2046 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002047 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2048 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002049 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2050 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002051 else
2052 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002053 glslang::TOperator op;
2054 if (node->getOp() == glslang::EOpPreIncrement ||
2055 node->getOp() == glslang::EOpPostIncrement)
2056 op = glslang::EOpAdd;
2057 else
2058 op = glslang::EOpSub;
2059
John Kessenichead86222018-03-28 18:01:20 -06002060 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002061 convertGlslangToSpvType(node->getType()), operand, one,
2062 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002063 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002064
2065 // The result of operation is always stored, but conditionally the
2066 // consumed result. The consumed result is always an r-value.
2067 builder.accessChainStore(result);
2068 builder.clearAccessChain();
2069 if (node->getOp() == glslang::EOpPreIncrement ||
2070 node->getOp() == glslang::EOpPreDecrement)
2071 builder.setAccessChainRValue(result);
2072 else
2073 builder.setAccessChainRValue(operand);
2074 }
2075
2076 return false;
2077
2078 case glslang::EOpEmitStreamVertex:
2079 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2080 return false;
2081 case glslang::EOpEndStreamPrimitive:
2082 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2083 return false;
2084
2085 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002086 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002087 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002088 }
John Kessenich140f3df2015-06-26 16:58:36 -06002089}
2090
2091bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2092{
qining27e04a02016-04-14 16:40:20 -04002093 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2094 if (node->getType().getQualifier().isSpecConstant())
2095 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2096
John Kessenichfc51d282015-08-19 13:34:18 -06002097 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002098 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2099 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002100
2101 // try texturing
2102 result = createImageTextureFunctionCall(node);
2103 if (result != spv::NoResult) {
2104 builder.clearAccessChain();
2105 builder.setAccessChainRValue(result);
2106
2107 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002108 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002109#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002110 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002111#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002112 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002113 // "imageStore" is a special case, which has no result
2114 return false;
2115 }
John Kessenichfc51d282015-08-19 13:34:18 -06002116
John Kessenich140f3df2015-06-26 16:58:36 -06002117 glslang::TOperator binOp = glslang::EOpNull;
2118 bool reduceComparison = true;
2119 bool isMatrix = false;
2120 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002121 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002122
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002123 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2124
John Kessenich140f3df2015-06-26 16:58:36 -06002125 assert(node->getOp());
2126
John Kessenichf6640762016-08-01 19:44:00 -06002127 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002128
2129 switch (node->getOp()) {
2130 case glslang::EOpSequence:
2131 {
2132 if (preVisit)
2133 ++sequenceDepth;
2134 else
2135 --sequenceDepth;
2136
2137 if (sequenceDepth == 1) {
2138 // If this is the parent node of all the functions, we want to see them
2139 // early, so all call points have actual SPIR-V functions to reference.
2140 // In all cases, still let the traverser visit the children for us.
2141 makeFunctions(node->getAsAggregate()->getSequence());
2142
John Kessenich6fccb3c2016-09-19 16:01:41 -06002143 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002144 // anything else gets there, so visit out of order, doing them all now.
2145 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2146
John Kessenich6a60c2f2016-12-08 21:01:59 -07002147 // 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 -06002148 // so do them manually.
2149 visitFunctions(node->getAsAggregate()->getSequence());
2150
2151 return false;
2152 }
2153
2154 return true;
2155 }
2156 case glslang::EOpLinkerObjects:
2157 {
2158 if (visit == glslang::EvPreVisit)
2159 linkageOnly = true;
2160 else
2161 linkageOnly = false;
2162
2163 return true;
2164 }
2165 case glslang::EOpComma:
2166 {
2167 // processing from left to right naturally leaves the right-most
2168 // lying around in the access chain
2169 glslang::TIntermSequence& glslangOperands = node->getSequence();
2170 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2171 glslangOperands[i]->traverse(this);
2172
2173 return false;
2174 }
2175 case glslang::EOpFunction:
2176 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002177 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002178 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002180 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002181 } else {
2182 handleFunctionEntry(node);
2183 }
2184 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002185 if (inEntryPoint)
2186 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002187 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002188 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002189 }
2190
2191 return true;
2192 case glslang::EOpParameters:
2193 // Parameters will have been consumed by EOpFunction processing, but not
2194 // the body, so we still visited the function node's children, making this
2195 // child redundant.
2196 return false;
2197 case glslang::EOpFunctionCall:
2198 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002199 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002200 if (node->isUserDefined())
2201 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002202 // 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 -07002203 if (result) {
2204 builder.clearAccessChain();
2205 builder.setAccessChainRValue(result);
2206 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002207 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002208
2209 return false;
2210 }
2211 case glslang::EOpConstructMat2x2:
2212 case glslang::EOpConstructMat2x3:
2213 case glslang::EOpConstructMat2x4:
2214 case glslang::EOpConstructMat3x2:
2215 case glslang::EOpConstructMat3x3:
2216 case glslang::EOpConstructMat3x4:
2217 case glslang::EOpConstructMat4x2:
2218 case glslang::EOpConstructMat4x3:
2219 case glslang::EOpConstructMat4x4:
2220 case glslang::EOpConstructDMat2x2:
2221 case glslang::EOpConstructDMat2x3:
2222 case glslang::EOpConstructDMat2x4:
2223 case glslang::EOpConstructDMat3x2:
2224 case glslang::EOpConstructDMat3x3:
2225 case glslang::EOpConstructDMat3x4:
2226 case glslang::EOpConstructDMat4x2:
2227 case glslang::EOpConstructDMat4x3:
2228 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002229 case glslang::EOpConstructIMat2x2:
2230 case glslang::EOpConstructIMat2x3:
2231 case glslang::EOpConstructIMat2x4:
2232 case glslang::EOpConstructIMat3x2:
2233 case glslang::EOpConstructIMat3x3:
2234 case glslang::EOpConstructIMat3x4:
2235 case glslang::EOpConstructIMat4x2:
2236 case glslang::EOpConstructIMat4x3:
2237 case glslang::EOpConstructIMat4x4:
2238 case glslang::EOpConstructUMat2x2:
2239 case glslang::EOpConstructUMat2x3:
2240 case glslang::EOpConstructUMat2x4:
2241 case glslang::EOpConstructUMat3x2:
2242 case glslang::EOpConstructUMat3x3:
2243 case glslang::EOpConstructUMat3x4:
2244 case glslang::EOpConstructUMat4x2:
2245 case glslang::EOpConstructUMat4x3:
2246 case glslang::EOpConstructUMat4x4:
2247 case glslang::EOpConstructBMat2x2:
2248 case glslang::EOpConstructBMat2x3:
2249 case glslang::EOpConstructBMat2x4:
2250 case glslang::EOpConstructBMat3x2:
2251 case glslang::EOpConstructBMat3x3:
2252 case glslang::EOpConstructBMat3x4:
2253 case glslang::EOpConstructBMat4x2:
2254 case glslang::EOpConstructBMat4x3:
2255 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002256 case glslang::EOpConstructF16Mat2x2:
2257 case glslang::EOpConstructF16Mat2x3:
2258 case glslang::EOpConstructF16Mat2x4:
2259 case glslang::EOpConstructF16Mat3x2:
2260 case glslang::EOpConstructF16Mat3x3:
2261 case glslang::EOpConstructF16Mat3x4:
2262 case glslang::EOpConstructF16Mat4x2:
2263 case glslang::EOpConstructF16Mat4x3:
2264 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002265 isMatrix = true;
2266 // fall through
2267 case glslang::EOpConstructFloat:
2268 case glslang::EOpConstructVec2:
2269 case glslang::EOpConstructVec3:
2270 case glslang::EOpConstructVec4:
2271 case glslang::EOpConstructDouble:
2272 case glslang::EOpConstructDVec2:
2273 case glslang::EOpConstructDVec3:
2274 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002275 case glslang::EOpConstructFloat16:
2276 case glslang::EOpConstructF16Vec2:
2277 case glslang::EOpConstructF16Vec3:
2278 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002279 case glslang::EOpConstructBool:
2280 case glslang::EOpConstructBVec2:
2281 case glslang::EOpConstructBVec3:
2282 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002283 case glslang::EOpConstructInt8:
2284 case glslang::EOpConstructI8Vec2:
2285 case glslang::EOpConstructI8Vec3:
2286 case glslang::EOpConstructI8Vec4:
2287 case glslang::EOpConstructUint8:
2288 case glslang::EOpConstructU8Vec2:
2289 case glslang::EOpConstructU8Vec3:
2290 case glslang::EOpConstructU8Vec4:
2291 case glslang::EOpConstructInt16:
2292 case glslang::EOpConstructI16Vec2:
2293 case glslang::EOpConstructI16Vec3:
2294 case glslang::EOpConstructI16Vec4:
2295 case glslang::EOpConstructUint16:
2296 case glslang::EOpConstructU16Vec2:
2297 case glslang::EOpConstructU16Vec3:
2298 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002299 case glslang::EOpConstructInt:
2300 case glslang::EOpConstructIVec2:
2301 case glslang::EOpConstructIVec3:
2302 case glslang::EOpConstructIVec4:
2303 case glslang::EOpConstructUint:
2304 case glslang::EOpConstructUVec2:
2305 case glslang::EOpConstructUVec3:
2306 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002307 case glslang::EOpConstructInt64:
2308 case glslang::EOpConstructI64Vec2:
2309 case glslang::EOpConstructI64Vec3:
2310 case glslang::EOpConstructI64Vec4:
2311 case glslang::EOpConstructUint64:
2312 case glslang::EOpConstructU64Vec2:
2313 case glslang::EOpConstructU64Vec3:
2314 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002315 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002316 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002317 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002318 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002319 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002320 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002321 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002322 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002323 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002324 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002325 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002326 else if (node->getOp() == glslang::EOpConstructStruct ||
2327 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2328 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002329 std::vector<spv::Id> constituents;
2330 for (int c = 0; c < (int)arguments.size(); ++c)
2331 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002332 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002333 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002334 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002335 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002336 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002337
2338 builder.clearAccessChain();
2339 builder.setAccessChainRValue(constructed);
2340
2341 return false;
2342 }
2343
2344 // These six are component-wise compares with component-wise results.
2345 // Forward on to createBinaryOperation(), requesting a vector result.
2346 case glslang::EOpLessThan:
2347 case glslang::EOpGreaterThan:
2348 case glslang::EOpLessThanEqual:
2349 case glslang::EOpGreaterThanEqual:
2350 case glslang::EOpVectorEqual:
2351 case glslang::EOpVectorNotEqual:
2352 {
2353 // Map the operation to a binary
2354 binOp = node->getOp();
2355 reduceComparison = false;
2356 switch (node->getOp()) {
2357 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2358 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2359 default: binOp = node->getOp(); break;
2360 }
2361
2362 break;
2363 }
2364 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002365 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002366 binOp = glslang::EOpMul;
2367 break;
2368 case glslang::EOpOuterProduct:
2369 // two vectors multiplied to make a matrix
2370 binOp = glslang::EOpOuterProduct;
2371 break;
2372 case glslang::EOpDot:
2373 {
qining25262b32016-05-06 17:25:16 -04002374 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002375 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002376 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002377 binOp = glslang::EOpMul;
2378 break;
2379 }
2380 case glslang::EOpMod:
2381 // when an aggregate, this is the floating-point mod built-in function,
2382 // which can be emitted by the one in createBinaryOperation()
2383 binOp = glslang::EOpMod;
2384 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002385 case glslang::EOpEmitVertex:
2386 case glslang::EOpEndPrimitive:
2387 case glslang::EOpBarrier:
2388 case glslang::EOpMemoryBarrier:
2389 case glslang::EOpMemoryBarrierAtomicCounter:
2390 case glslang::EOpMemoryBarrierBuffer:
2391 case glslang::EOpMemoryBarrierImage:
2392 case glslang::EOpMemoryBarrierShared:
2393 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002394 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002395 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002396 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002397 case glslang::EOpWorkgroupMemoryBarrier:
2398 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002399 case glslang::EOpSubgroupBarrier:
2400 case glslang::EOpSubgroupMemoryBarrier:
2401 case glslang::EOpSubgroupMemoryBarrierBuffer:
2402 case glslang::EOpSubgroupMemoryBarrierImage:
2403 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002404 noReturnValue = true;
2405 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2406 break;
2407
Jeff Bolz36831c92018-09-05 10:11:41 -05002408 case glslang::EOpAtomicStore:
2409 noReturnValue = true;
2410 // fallthrough
2411 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002412 case glslang::EOpAtomicAdd:
2413 case glslang::EOpAtomicMin:
2414 case glslang::EOpAtomicMax:
2415 case glslang::EOpAtomicAnd:
2416 case glslang::EOpAtomicOr:
2417 case glslang::EOpAtomicXor:
2418 case glslang::EOpAtomicExchange:
2419 case glslang::EOpAtomicCompSwap:
2420 atomic = true;
2421 break;
2422
John Kessenich0d0c6d32017-07-23 16:08:26 -06002423 case glslang::EOpAtomicCounterAdd:
2424 case glslang::EOpAtomicCounterSubtract:
2425 case glslang::EOpAtomicCounterMin:
2426 case glslang::EOpAtomicCounterMax:
2427 case glslang::EOpAtomicCounterAnd:
2428 case glslang::EOpAtomicCounterOr:
2429 case glslang::EOpAtomicCounterXor:
2430 case glslang::EOpAtomicCounterExchange:
2431 case glslang::EOpAtomicCounterCompSwap:
2432 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2433 builder.addCapability(spv::CapabilityAtomicStorageOps);
2434 atomic = true;
2435 break;
2436
Chao Chen3c366992018-09-19 11:41:59 -07002437#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002438 case glslang::EOpIgnoreIntersectionNV:
2439 case glslang::EOpTerminateRayNV:
2440 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002441 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002442 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2443 noReturnValue = true;
2444 break;
2445#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002446 case glslang::EOpCooperativeMatrixLoad:
2447 case glslang::EOpCooperativeMatrixStore:
2448 noReturnValue = true;
2449 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002450 case glslang::EOpBeginInvocationInterlock:
2451 case glslang::EOpEndInvocationInterlock:
2452 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2453 noReturnValue = true;
2454 break;
Chao Chen3c366992018-09-19 11:41:59 -07002455
John Kessenich140f3df2015-06-26 16:58:36 -06002456 default:
2457 break;
2458 }
2459
2460 //
2461 // See if it maps to a regular operation.
2462 //
John Kessenich140f3df2015-06-26 16:58:36 -06002463 if (binOp != glslang::EOpNull) {
2464 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2465 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2466 assert(left && right);
2467
2468 builder.clearAccessChain();
2469 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002470 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002471
2472 builder.clearAccessChain();
2473 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002474 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002475
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002476 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002477 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002478 TranslateNoContractionDecoration(node->getType().getQualifier()),
2479 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002480 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002481 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002482 left->getType().getBasicType(), reduceComparison);
2483
2484 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002485 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002486 builder.clearAccessChain();
2487 builder.setAccessChainRValue(result);
2488
2489 return false;
2490 }
2491
John Kessenich426394d2015-07-23 10:22:48 -06002492 //
2493 // Create the list of operands.
2494 //
John Kessenich140f3df2015-06-26 16:58:36 -06002495 glslang::TIntermSequence& glslangOperands = node->getSequence();
2496 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002497 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002498 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002499 // special case l-value operands; there are just a few
2500 bool lvalue = false;
2501 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002502 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002503 case glslang::EOpModf:
2504 if (arg == 1)
2505 lvalue = true;
2506 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002507 case glslang::EOpInterpolateAtSample:
2508 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002509#ifdef AMD_EXTENSIONS
2510 case glslang::EOpInterpolateAtVertex:
2511#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002512 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002513 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002514
2515 // Does it need a swizzle inversion? If so, evaluation is inverted;
2516 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002517 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002518 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2519 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2520 }
Rex Xu7a26c172015-12-08 17:12:09 +08002521 break;
Rex Xud4782c12015-09-06 16:30:11 +08002522 case glslang::EOpAtomicAdd:
2523 case glslang::EOpAtomicMin:
2524 case glslang::EOpAtomicMax:
2525 case glslang::EOpAtomicAnd:
2526 case glslang::EOpAtomicOr:
2527 case glslang::EOpAtomicXor:
2528 case glslang::EOpAtomicExchange:
2529 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002530 case glslang::EOpAtomicLoad:
2531 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002532 case glslang::EOpAtomicCounterAdd:
2533 case glslang::EOpAtomicCounterSubtract:
2534 case glslang::EOpAtomicCounterMin:
2535 case glslang::EOpAtomicCounterMax:
2536 case glslang::EOpAtomicCounterAnd:
2537 case glslang::EOpAtomicCounterOr:
2538 case glslang::EOpAtomicCounterXor:
2539 case glslang::EOpAtomicCounterExchange:
2540 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002541 if (arg == 0)
2542 lvalue = true;
2543 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002544 case glslang::EOpAddCarry:
2545 case glslang::EOpSubBorrow:
2546 if (arg == 2)
2547 lvalue = true;
2548 break;
2549 case glslang::EOpUMulExtended:
2550 case glslang::EOpIMulExtended:
2551 if (arg >= 2)
2552 lvalue = true;
2553 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002554 case glslang::EOpCooperativeMatrixLoad:
2555 if (arg == 0 || arg == 1)
2556 lvalue = true;
2557 break;
2558 case glslang::EOpCooperativeMatrixStore:
2559 if (arg == 1)
2560 lvalue = true;
2561 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002562 default:
2563 break;
2564 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002565 builder.clearAccessChain();
2566 if (invertedType != spv::NoType && arg == 0)
2567 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2568 else
2569 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002570
2571 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2572 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2573
2574 if (arg == 1) {
2575 // fold "element" parameter into the access chain
2576 spv::Builder::AccessChain save = builder.getAccessChain();
2577 builder.clearAccessChain();
2578 glslangOperands[2]->traverse(this);
2579
2580 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2581
2582 builder.setAccessChain(save);
2583
2584 // Point to the first element of the array.
2585 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002586 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002587
2588 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2589 unsigned int alignment = builder.getAccessChain().alignment;
2590
2591 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2592 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2593 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2594 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2595 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2596 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2597 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2598 }
2599
2600 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2601
2602 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2603 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2604 }
2605
2606 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2607 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2608 }
2609 } else if (arg == 2) {
2610 continue;
2611 }
2612 }
2613
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002614 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002615 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002616 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2617 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2618 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002619 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002620 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002621 }
John Kessenich140f3df2015-06-26 16:58:36 -06002622 }
John Kessenich426394d2015-07-23 10:22:48 -06002623
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002624 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002625 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2626 std::vector<spv::IdImmediate> idImmOps;
2627
2628 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2629 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2630 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2631 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2632 // get the pointee type
2633 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2634 assert(builder.isCooperativeMatrixType(typeId));
2635 // do the op
2636 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2637 // store the result to the pointer (out param 'm')
2638 builder.createStore(result, operands[0]);
2639 result = 0;
2640 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2641 std::vector<spv::IdImmediate> idImmOps;
2642
2643 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2644 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2645 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2646 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2647 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2648
2649 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2650 result = 0;
2651 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002652 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002653 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002654 } else {
2655 // Pass through to generic operations.
2656 switch (glslangOperands.size()) {
2657 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002658 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002659 break;
2660 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002661 {
2662 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002663 TranslateNoContractionDecoration(node->getType().getQualifier()),
2664 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002665 result = createUnaryOperation(
2666 node->getOp(), decorations,
2667 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002668 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002669 }
John Kessenich426394d2015-07-23 10:22:48 -06002670 break;
2671 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002672 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002673 break;
2674 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002675 if (invertedType)
2676 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002677 }
2678
2679 if (noReturnValue)
2680 return false;
2681
2682 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002683 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002684 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002685 } else {
2686 builder.clearAccessChain();
2687 builder.setAccessChainRValue(result);
2688 return false;
2689 }
2690}
2691
John Kessenich433e9ff2017-01-26 20:31:11 -07002692// This path handles both if-then-else and ?:
2693// The if-then-else has a node type of void, while
2694// ?: has either a void or a non-void node type
2695//
2696// Leaving the result, when not void:
2697// GLSL only has r-values as the result of a :?, but
2698// if we have an l-value, that can be more efficient if it will
2699// become the base of a complex r-value expression, because the
2700// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002701bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2702{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002703 // see if OpSelect can handle it
2704 const auto isOpSelectable = [&]() {
2705 if (node->getBasicType() == glslang::EbtVoid)
2706 return false;
2707 // OpSelect can do all other types starting with SPV 1.4
2708 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2709 // pre-1.4, only scalars and vectors can be handled
2710 if ((!node->getType().isScalar() && !node->getType().isVector()))
2711 return false;
2712 }
2713 return true;
2714 };
2715
John Kessenich4bee5312018-02-20 21:29:05 -07002716 // See if it simple and safe, or required, to execute both sides.
2717 // Crucially, side effects must be either semantically required or avoided,
2718 // and there are performance trade-offs.
2719 // Return true if required or a good idea (and safe) to execute both sides,
2720 // false otherwise.
2721 const auto bothSidesPolicy = [&]() -> bool {
2722 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002723 if (node->getTrueBlock() == nullptr ||
2724 node->getFalseBlock() == nullptr)
2725 return false;
2726
John Kessenich4bee5312018-02-20 21:29:05 -07002727 // required? (unless we write additional code to look for side effects
2728 // and make performance trade-offs if none are present)
2729 if (!node->getShortCircuit())
2730 return true;
2731
2732 // if not required to execute both, decide based on performance/practicality...
2733
John Kessenich0c1e71a2019-01-10 18:23:06 +07002734 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002735 return false;
2736
John Kessenich433e9ff2017-01-26 20:31:11 -07002737 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2738 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2739
2740 // return true if a single operand to ? : is okay for OpSelect
2741 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002742 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002743 };
2744
2745 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2746 operandOkay(node->getFalseBlock()->getAsTyped());
2747 };
2748
John Kessenich4bee5312018-02-20 21:29:05 -07002749 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2750 // emit the condition before doing anything with selection
2751 node->getCondition()->traverse(this);
2752 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2753
2754 // Find a way of executing both sides and selecting the right result.
2755 const auto executeBothSides = [&]() -> void {
2756 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002757 node->getTrueBlock()->traverse(this);
2758 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2759 node->getFalseBlock()->traverse(this);
2760 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2761
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002762 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002763
John Kessenich4bee5312018-02-20 21:29:05 -07002764 // done if void
2765 if (node->getBasicType() == glslang::EbtVoid)
2766 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002767
John Kessenich4bee5312018-02-20 21:29:05 -07002768 // emit code to select between trueValue and falseValue
2769
2770 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002771 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002772 // Emit OpSelect for this selection.
2773
2774 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002775 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2776 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002777 condition = builder.smearScalar(spv::NoPrecision, condition,
2778 builder.makeVectorType(builder.makeBoolType(),
2779 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002780 }
John Kessenich4bee5312018-02-20 21:29:05 -07002781
2782 // OpSelect
2783 result = builder.createTriOp(spv::OpSelect,
2784 convertGlslangToSpvType(node->getType()), condition,
2785 trueValue, falseValue);
2786
2787 builder.clearAccessChain();
2788 builder.setAccessChainRValue(result);
2789 } else {
2790 // We need control flow to select the result.
2791 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2792 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2793
2794 // Selection control:
2795 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2796
2797 // make an "if" based on the value created by the condition
2798 spv::Builder::If ifBuilder(condition, control, builder);
2799
2800 // emit the "then" statement
2801 builder.createStore(trueValue, result);
2802 ifBuilder.makeBeginElse();
2803 // emit the "else" statement
2804 builder.createStore(falseValue, result);
2805
2806 // finish off the control flow
2807 ifBuilder.makeEndIf();
2808
2809 builder.clearAccessChain();
2810 builder.setAccessChainLValue(result);
2811 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002812 };
2813
John Kessenich4bee5312018-02-20 21:29:05 -07002814 // Execute the one side needed, as per the condition
2815 const auto executeOneSide = [&]() {
2816 // Always emit control flow.
2817 if (node->getBasicType() != glslang::EbtVoid)
2818 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002819
John Kessenich4bee5312018-02-20 21:29:05 -07002820 // Selection control:
2821 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2822
2823 // make an "if" based on the value created by the condition
2824 spv::Builder::If ifBuilder(condition, control, builder);
2825
2826 // emit the "then" statement
2827 if (node->getTrueBlock() != nullptr) {
2828 node->getTrueBlock()->traverse(this);
2829 if (result != spv::NoResult)
2830 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2831 }
2832
2833 if (node->getFalseBlock() != nullptr) {
2834 ifBuilder.makeBeginElse();
2835 // emit the "else" statement
2836 node->getFalseBlock()->traverse(this);
2837 if (result != spv::NoResult)
2838 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2839 }
2840
2841 // finish off the control flow
2842 ifBuilder.makeEndIf();
2843
2844 if (result != spv::NoResult) {
2845 builder.clearAccessChain();
2846 builder.setAccessChainLValue(result);
2847 }
2848 };
2849
2850 // Try for OpSelect (or a requirement to execute both sides)
2851 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002852 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2853 if (node->getType().getQualifier().isSpecConstant())
2854 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002855 executeBothSides();
2856 } else
2857 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002858
2859 return false;
2860}
2861
2862bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2863{
2864 // emit and get the condition before doing anything with switch
2865 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002866 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002867
Rex Xu57e65922017-07-04 23:23:40 +08002868 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002869 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002870
John Kessenich140f3df2015-06-26 16:58:36 -06002871 // browse the children to sort out code segments
2872 int defaultSegment = -1;
2873 std::vector<TIntermNode*> codeSegments;
2874 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2875 std::vector<int> caseValues;
2876 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2877 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2878 TIntermNode* child = *c;
2879 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002880 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002881 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002882 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002883 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2884 } else
2885 codeSegments.push_back(child);
2886 }
2887
qining25262b32016-05-06 17:25:16 -04002888 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002889 // statements between the last case and the end of the switch statement
2890 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2891 (int)codeSegments.size() == defaultSegment)
2892 codeSegments.push_back(nullptr);
2893
2894 // make the switch statement
2895 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002896 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002897
2898 // emit all the code in the segments
2899 breakForLoop.push(false);
2900 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2901 builder.nextSwitchSegment(segmentBlocks, s);
2902 if (codeSegments[s])
2903 codeSegments[s]->traverse(this);
2904 else
2905 builder.addSwitchBreak();
2906 }
2907 breakForLoop.pop();
2908
2909 builder.endSwitch(segmentBlocks);
2910
2911 return false;
2912}
2913
2914void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2915{
2916 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002917 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002918
2919 builder.clearAccessChain();
2920 builder.setAccessChainRValue(constant);
2921}
2922
2923bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2924{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002925 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002926 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002927
2928 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002929 std::vector<unsigned int> operands;
2930 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002931
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002932 // Spec requires back edges to target header blocks, and every header block
2933 // must dominate its merge block. Make a header block first to ensure these
2934 // conditions are met. By definition, it will contain OpLoopMerge, followed
2935 // by a block-ending branch. But we don't want to put any other body/test
2936 // instructions in it, since the body/test may have arbitrary instructions,
2937 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002938 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002939 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002940 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002941 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002942 spv::Block& test = builder.makeNewBlock();
2943 builder.createBranch(&test);
2944
2945 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002946 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002947 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002948 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2949
2950 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002951 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002952 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002953 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002954 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002955 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002956
2957 builder.setBuildPoint(&blocks.continue_target);
2958 if (node->getTerminal())
2959 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002960 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002961 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002962 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002963 builder.createBranch(&blocks.body);
2964
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002965 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002966 builder.setBuildPoint(&blocks.body);
2967 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002968 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002969 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002970 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002971
2972 builder.setBuildPoint(&blocks.continue_target);
2973 if (node->getTerminal())
2974 node->getTerminal()->traverse(this);
2975 if (node->getTest()) {
2976 node->getTest()->traverse(this);
2977 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002978 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002979 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002980 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002981 // TODO: unless there was a break/return/discard instruction
2982 // somewhere in the body, this is an infinite loop, so we should
2983 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002984 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002985 }
John Kessenich140f3df2015-06-26 16:58:36 -06002986 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002987 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002988 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002989 return false;
2990}
2991
2992bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2993{
2994 if (node->getExpression())
2995 node->getExpression()->traverse(this);
2996
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002997 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002998
John Kessenich140f3df2015-06-26 16:58:36 -06002999 switch (node->getFlowOp()) {
3000 case glslang::EOpKill:
3001 builder.makeDiscard();
3002 break;
3003 case glslang::EOpBreak:
3004 if (breakForLoop.top())
3005 builder.createLoopExit();
3006 else
3007 builder.addSwitchBreak();
3008 break;
3009 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003010 builder.createLoopContinue();
3011 break;
3012 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003013 if (node->getExpression()) {
3014 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3015 spv::Id returnId = accessChainLoad(glslangReturnType);
3016 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3017 builder.clearAccessChain();
3018 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3019 builder.setAccessChainLValue(copyId);
3020 multiTypeStore(glslangReturnType, returnId);
3021 returnId = builder.createLoad(copyId);
3022 }
3023 builder.makeReturn(false, returnId);
3024 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003025 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003026
3027 builder.clearAccessChain();
3028 break;
3029
3030 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003031 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 }
3034
3035 return false;
3036}
3037
3038spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
3039{
qining25262b32016-05-06 17:25:16 -04003040 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003041 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003042 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003043 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003044 spv::Id result = createSpvConstant(*node);
3045 if (result != spv::NoResult)
3046 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003047 }
3048
3049 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003050 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003051 spv::Id spvType = convertGlslangToSpvType(node->getType());
3052
Rex Xucabbb782017-03-24 13:41:14 +08003053 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3054 node->getType().containsBasicType(glslang::EbtInt16) ||
3055 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003056 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003057 switch (storageClass) {
3058 case spv::StorageClassInput:
3059 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003060 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003061 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003062 break;
3063 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003064 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003065 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003066 break;
3067 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003068 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003069 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3070 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003071 else
3072 builder.addCapability(spv::CapabilityStorageUniform16);
3073 break;
3074 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003075 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003076 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3077 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3078 break;
3079 default:
3080 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003081 }
3082 }
Rex Xuf89ad982017-04-07 23:22:33 +08003083
John Kessenich312dcfb2018-07-03 13:19:51 -06003084 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3085 node->getType().containsBasicType(glslang::EbtUint8);
3086 if (contains8BitType) {
3087 if (storageClass == spv::StorageClassPushConstant) {
3088 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3089 builder.addCapability(spv::CapabilityStoragePushConstant8);
3090 } else if (storageClass == spv::StorageClassUniform) {
3091 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3092 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003093 } else if (storageClass == spv::StorageClassStorageBuffer) {
3094 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3095 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003096 }
3097 }
3098
John Kessenich140f3df2015-06-26 16:58:36 -06003099 const char* name = node->getName().c_str();
3100 if (glslang::IsAnonymous(name))
3101 name = "";
3102
3103 return builder.createVariable(storageClass, spvType, name);
3104}
3105
3106// Return type Id of the sampled type.
3107spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3108{
3109 switch (sampler.type) {
3110 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003111#ifdef AMD_EXTENSIONS
3112 case glslang::EbtFloat16:
3113 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3114 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3115 return builder.makeFloatType(16);
3116#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003117 case glslang::EbtInt: return builder.makeIntType(32);
3118 case glslang::EbtUint: return builder.makeUintType(32);
3119 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003120 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003121 return builder.makeFloatType(32);
3122 }
3123}
3124
John Kessenich8c8505c2016-07-26 12:50:38 -06003125// If node is a swizzle operation, return the type that should be used if
3126// the swizzle base is first consumed by another operation, before the swizzle
3127// is applied.
3128spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3129{
John Kessenichecba76f2017-01-06 00:34:48 -07003130 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003131 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3132 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3133 else
3134 return spv::NoType;
3135}
3136
3137// When inverting a swizzle with a parent op, this function
3138// will apply the swizzle operation to a completed parent operation.
3139spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3140{
3141 std::vector<unsigned> swizzle;
3142 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3143 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3144}
3145
John Kessenich8c8505c2016-07-26 12:50:38 -06003146// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3147void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3148{
3149 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3150 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3151 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3152}
3153
John Kessenich3ac051e2015-12-20 11:29:16 -07003154// Convert from a glslang type to an SPV type, by calling into a
3155// recursive version of this function. This establishes the inherited
3156// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003157spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003158{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003159 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003160}
3161
3162// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003163// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003164// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003165spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003166 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3167 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003168{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003169 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003170
3171 switch (type.getBasicType()) {
3172 case glslang::EbtVoid:
3173 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003174 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003175 break;
3176 case glslang::EbtFloat:
3177 spvType = builder.makeFloatType(32);
3178 break;
3179 case glslang::EbtDouble:
3180 spvType = builder.makeFloatType(64);
3181 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003182 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003183 spvType = builder.makeFloatType(16);
3184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003186 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3187 // a 32-bit int where non-0 means true.
3188 if (explicitLayout != glslang::ElpNone)
3189 spvType = builder.makeUintType(32);
3190 else
3191 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003192 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003193 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003194 spvType = builder.makeIntType(8);
3195 break;
3196 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003197 spvType = builder.makeUintType(8);
3198 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003199 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003200 spvType = builder.makeIntType(16);
3201 break;
3202 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003203 spvType = builder.makeUintType(16);
3204 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003205 case glslang::EbtInt:
3206 spvType = builder.makeIntType(32);
3207 break;
3208 case glslang::EbtUint:
3209 spvType = builder.makeUintType(32);
3210 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003211 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003212 spvType = builder.makeIntType(64);
3213 break;
3214 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003215 spvType = builder.makeUintType(64);
3216 break;
John Kessenich426394d2015-07-23 10:22:48 -06003217 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003218 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003219 spvType = builder.makeUintType(32);
3220 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003221#ifdef NV_EXTENSIONS
3222 case glslang::EbtAccStructNV:
3223 spvType = builder.makeAccelerationStructureNVType();
3224 break;
3225#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003226 case glslang::EbtSampler:
3227 {
3228 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003229 if (sampler.sampler) {
3230 // pure sampler
3231 spvType = builder.makeSamplerType();
3232 } else {
3233 // an image is present, make its type
3234 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3235 sampler.image ? 2 : 1, TranslateImageFormat(type));
3236 if (sampler.combined) {
3237 // already has both image and sampler, make the combined type
3238 spvType = builder.makeSampledImageType(spvType);
3239 }
John Kessenich55e7d112015-11-15 21:33:39 -07003240 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003241 }
John Kessenich140f3df2015-06-26 16:58:36 -06003242 break;
3243 case glslang::EbtStruct:
3244 case glslang::EbtBlock:
3245 {
3246 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003247 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003248
3249 // Try to share structs for different layouts, but not yet for other
3250 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003251 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003252 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003253 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003254 break;
3255
3256 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003257 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003258 memberRemapper[glslangMembers].resize(glslangMembers->size());
3259 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003260 }
3261 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003262 case glslang::EbtReference:
3263 {
3264 // Make the forward pointer, then recurse to convert the structure type, then
3265 // patch up the forward pointer with a real pointer type.
3266 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3267 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3268 forwardPointers[type.getReferentType()] = forwardId;
3269 }
3270 spvType = forwardPointers[type.getReferentType()];
3271 if (!forwardReferenceOnly) {
3272 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3273 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3274 forwardPointers[type.getReferentType()],
3275 referentType);
3276 }
3277 }
3278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003280 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003281 break;
3282 }
3283
3284 if (type.isMatrix())
3285 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3286 else {
3287 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3288 if (type.getVectorSize() > 1)
3289 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3290 }
3291
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003292 if (type.isCoopMat()) {
3293 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3294 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3295 if (type.getBasicType() == glslang::EbtFloat16)
3296 builder.addCapability(spv::CapabilityFloat16);
3297
3298 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3299 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3300 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3301
3302 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3303 }
3304
John Kessenich140f3df2015-06-26 16:58:36 -06003305 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003306 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3307
John Kessenichc9a80832015-09-12 12:17:44 -06003308 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003309 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003310 // We need to decorate array strides for types needing explicit layout, except blocks.
3311 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003312 // Use a dummy glslang type for querying internal strides of
3313 // arrays of arrays, but using just a one-dimensional array.
3314 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003315 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3316 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003317
3318 // Will compute the higher-order strides here, rather than making a whole
3319 // pile of types and doing repetitive recursion on their contents.
3320 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3321 }
John Kessenichf8842e52016-01-04 19:22:56 -07003322
3323 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003324 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003325 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003326 if (stride > 0)
3327 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003328 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003329 }
3330 } else {
3331 // single-dimensional array, and don't yet have stride
3332
John Kessenichf8842e52016-01-04 19:22:56 -07003333 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003334 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3335 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003336 }
John Kessenich31ed4832015-09-09 17:51:38 -06003337
John Kessenichead86222018-03-28 18:01:20 -06003338 // Do the outer dimension, which might not be known for a runtime-sized array.
3339 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3340 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003341 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003342 else {
3343 if (!lastBufferBlockMember) {
3344 builder.addExtension("SPV_EXT_descriptor_indexing");
3345 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3346 }
John Kessenichead86222018-03-28 18:01:20 -06003347 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003348 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003349 if (stride > 0)
3350 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003351 }
3352
3353 return spvType;
3354}
3355
John Kessenich0e737842017-03-24 18:38:16 -06003356// TODO: this functionality should exist at a higher level, in creating the AST
3357//
3358// Identify interface members that don't have their required extension turned on.
3359//
3360bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3361{
Chao Chen3c366992018-09-19 11:41:59 -07003362#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003363 auto& extensions = glslangIntermediate->getRequestedExtensions();
3364
Rex Xubcf291a2017-03-29 23:01:36 +08003365 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3366 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3367 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003368 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3369 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3370 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003371
3372 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3373 if (member.getFieldName() == "gl_ViewportMask" &&
3374 extensions.find("GL_NV_viewport_array2") == extensions.end())
3375 return true;
3376 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3377 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3378 return true;
3379 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3380 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3381 return true;
3382 }
3383#endif
John Kessenich0e737842017-03-24 18:38:16 -06003384
3385 return false;
3386};
3387
John Kessenich6090df02016-06-30 21:18:02 -06003388// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3389// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3390// Mutually recursive with convertGlslangToSpvType().
3391spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3392 const glslang::TTypeList* glslangMembers,
3393 glslang::TLayoutPacking explicitLayout,
3394 const glslang::TQualifier& qualifier)
3395{
3396 // Create a vector of struct types for SPIR-V to consume
3397 std::vector<spv::Id> spvMembers;
3398 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 -06003399 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003400 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3401 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3402 if (glslangMember.hiddenMember()) {
3403 ++memberDelta;
3404 if (type.getBasicType() == glslang::EbtBlock)
3405 memberRemapper[glslangMembers][i] = -1;
3406 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003407 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003408 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003409 if (filterMember(glslangMember))
3410 continue;
3411 }
John Kessenich6090df02016-06-30 21:18:02 -06003412 // modify just this child's view of the qualifier
3413 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3414 InheritQualifiers(memberQualifier, qualifier);
3415
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003416 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003417 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003418 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003419
3420 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003421 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3422 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003423
3424 // Make forward pointers for any pointer members, and create a list of members to
3425 // convert to spirv types after creating the struct.
3426 if (glslangMember.getBasicType() == glslang::EbtReference) {
3427 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3428 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3429 }
3430 spvMembers.push_back(
3431 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3432 } else {
3433 spvMembers.push_back(
3434 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3435 }
John Kessenich6090df02016-06-30 21:18:02 -06003436 }
3437 }
3438
3439 // Make the SPIR-V type
3440 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003441 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003442 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3443
3444 // Decorate it
3445 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3446
John Kessenichd72f4882019-01-16 14:55:37 +07003447 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003448 auto it = deferredForwardPointers[i];
3449 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3450 }
3451
John Kessenich6090df02016-06-30 21:18:02 -06003452 return spvType;
3453}
3454
3455void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3456 const glslang::TTypeList* glslangMembers,
3457 glslang::TLayoutPacking explicitLayout,
3458 const glslang::TQualifier& qualifier,
3459 spv::Id spvType)
3460{
3461 // Name and decorate the non-hidden members
3462 int offset = -1;
3463 int locationOffset = 0; // for use within the members of this struct
3464 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3465 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3466 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003467 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003468 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003469 if (filterMember(glslangMember))
3470 continue;
3471 }
John Kessenich6090df02016-06-30 21:18:02 -06003472
3473 // modify just this child's view of the qualifier
3474 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3475 InheritQualifiers(memberQualifier, qualifier);
3476
3477 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003478 if (member < 0)
3479 continue;
3480
3481 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3482 builder.addMemberDecoration(spvType, member,
3483 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3484 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3485 // Add interpolation and auxiliary storage decorations only to
3486 // top-level members of Input and Output storage classes
3487 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3488 type.getQualifier().storage == glslang::EvqVaryingOut) {
3489 if (type.getBasicType() == glslang::EbtBlock ||
3490 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3491 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3492 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003493#ifdef NV_EXTENSIONS
3494 addMeshNVDecoration(spvType, member, memberQualifier);
3495#endif
John Kessenich6090df02016-06-30 21:18:02 -06003496 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003497 }
3498 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003499
John Kessenich5d610ee2018-03-07 18:05:55 -07003500 if (type.getBasicType() == glslang::EbtBlock &&
3501 qualifier.storage == glslang::EvqBuffer) {
3502 // Add memory decorations only to top-level members of shader storage block
3503 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003504 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003505 for (unsigned int i = 0; i < memory.size(); ++i)
3506 builder.addMemberDecoration(spvType, member, memory[i]);
3507 }
John Kessenich6090df02016-06-30 21:18:02 -06003508
John Kessenich5d610ee2018-03-07 18:05:55 -07003509 // Location assignment was already completed correctly by the front end,
3510 // just track whether a member needs to be decorated.
3511 // Ignore member locations if the container is an array, as that's
3512 // ill-specified and decisions have been made to not allow this.
3513 if (! type.isArray() && memberQualifier.hasLocation())
3514 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003515
John Kessenich5d610ee2018-03-07 18:05:55 -07003516 if (qualifier.hasLocation()) // track for upcoming inheritance
3517 locationOffset += glslangIntermediate->computeTypeLocationSize(
3518 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003519
John Kessenich5d610ee2018-03-07 18:05:55 -07003520 // component, XFB, others
3521 if (glslangMember.getQualifier().hasComponent())
3522 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3523 glslangMember.getQualifier().layoutComponent);
3524 if (glslangMember.getQualifier().hasXfbOffset())
3525 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3526 glslangMember.getQualifier().layoutXfbOffset);
3527 else if (explicitLayout != glslang::ElpNone) {
3528 // figure out what to do with offset, which is accumulating
3529 int nextOffset;
3530 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3531 if (offset >= 0)
3532 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3533 offset = nextOffset;
3534 }
John Kessenich6090df02016-06-30 21:18:02 -06003535
John Kessenich5d610ee2018-03-07 18:05:55 -07003536 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3537 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3538 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003539
John Kessenich5d610ee2018-03-07 18:05:55 -07003540 // built-in variable decorations
3541 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3542 if (builtIn != spv::BuiltInMax)
3543 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003544
John Kessenich5611c6d2018-04-05 11:25:02 -06003545 // nonuniform
3546 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3547
John Kessenichead86222018-03-28 18:01:20 -06003548 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3549 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3550 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3551 memberQualifier.semanticName);
3552 }
3553
chaoc771d89f2017-01-13 01:10:53 -08003554#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003555 if (builtIn == spv::BuiltInLayer) {
3556 // SPV_NV_viewport_array2 extension
3557 if (glslangMember.getQualifier().layoutViewportRelative){
3558 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3559 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3560 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003561 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003562 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3563 builder.addMemberDecoration(spvType, member,
3564 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3565 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3566 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3567 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003568 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003569 }
3570 if (glslangMember.getQualifier().layoutPassthrough) {
3571 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3572 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3573 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3574 }
chaoc771d89f2017-01-13 01:10:53 -08003575#endif
John Kessenich6090df02016-06-30 21:18:02 -06003576 }
3577
3578 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003579 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3580 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003581}
3582
John Kessenich6c292d32016-02-15 20:58:50 -07003583// Turn the expression forming the array size into an id.
3584// This is not quite trivial, because of specialization constants.
3585// Sometimes, a raw constant is turned into an Id, and sometimes
3586// a specialization constant expression is.
3587spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3588{
3589 // First, see if this is sized with a node, meaning a specialization constant:
3590 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3591 if (specNode != nullptr) {
3592 builder.clearAccessChain();
3593 specNode->traverse(this);
3594 return accessChainLoad(specNode->getAsTyped()->getType());
3595 }
qining25262b32016-05-06 17:25:16 -04003596
John Kessenich6c292d32016-02-15 20:58:50 -07003597 // Otherwise, need a compile-time (front end) size, get it:
3598 int size = arraySizes.getDimSize(dim);
3599 assert(size > 0);
3600 return builder.makeUintConstant(size);
3601}
3602
John Kessenich103bef92016-02-08 21:38:15 -07003603// Wrap the builder's accessChainLoad to:
3604// - localize handling of RelaxedPrecision
3605// - use the SPIR-V inferred type instead of another conversion of the glslang type
3606// (avoids unnecessary work and possible type punning for structures)
3607// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003608spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3609{
John Kessenich103bef92016-02-08 21:38:15 -07003610 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003611
3612 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3613 coherentFlags |= TranslateCoherent(type);
3614
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003615 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003616 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003617
John Kessenich5611c6d2018-04-05 11:25:02 -06003618 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003619 TranslateNonUniformDecoration(type.getQualifier()),
3620 nominalTypeId,
3621 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003622 TranslateMemoryScope(coherentFlags),
3623 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003624
3625 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003626 if (type.getBasicType() == glslang::EbtBool) {
3627 if (builder.isScalarType(nominalTypeId)) {
3628 // Conversion for bool
3629 spv::Id boolType = builder.makeBoolType();
3630 if (nominalTypeId != boolType)
3631 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3632 } else if (builder.isVectorType(nominalTypeId)) {
3633 // Conversion for bvec
3634 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3635 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3636 if (nominalTypeId != bvecType)
3637 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3638 }
3639 }
John Kessenich103bef92016-02-08 21:38:15 -07003640
3641 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003642}
3643
Rex Xu27253232016-02-23 17:51:09 +08003644// Wrap the builder's accessChainStore to:
3645// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003646//
3647// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003648void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3649{
3650 // Need to convert to abstract types when necessary
3651 if (type.getBasicType() == glslang::EbtBool) {
3652 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3653
3654 if (builder.isScalarType(nominalTypeId)) {
3655 // Conversion for bool
3656 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003657 if (nominalTypeId != boolType) {
3658 // keep these outside arguments, for determinant order-of-evaluation
3659 spv::Id one = builder.makeUintConstant(1);
3660 spv::Id zero = builder.makeUintConstant(0);
3661 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3662 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003663 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003664 } else if (builder.isVectorType(nominalTypeId)) {
3665 // Conversion for bvec
3666 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3667 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003668 if (nominalTypeId != bvecType) {
3669 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003670 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3671 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3672 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003673 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003674 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3675 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003676 }
3677 }
3678
Jeff Bolz36831c92018-09-05 10:11:41 -05003679 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3680 coherentFlags |= TranslateCoherent(type);
3681
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003682 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003683 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003684
Jeff Bolz36831c92018-09-05 10:11:41 -05003685 builder.accessChainStore(rvalue,
3686 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003687 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003688}
3689
John Kessenich4bf71552016-09-02 11:20:21 -06003690// For storing when types match at the glslang level, but not might match at the
3691// SPIR-V level.
3692//
3693// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003694// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003695// as in a member-decorated way.
3696//
3697// NOTE: This function can handle any store request; if it's not special it
3698// simplifies to a simple OpStore.
3699//
3700// Implicitly uses the existing builder.accessChain as the storage target.
3701void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3702{
John Kessenichb3e24e42016-09-11 12:33:43 -06003703 // we only do the complex path here if it's an aggregate
3704 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003705 accessChainStore(type, rValue);
3706 return;
3707 }
3708
John Kessenichb3e24e42016-09-11 12:33:43 -06003709 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003710 spv::Id rType = builder.getTypeId(rValue);
3711 spv::Id lValue = builder.accessChainGetLValue();
3712 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3713 if (lType == rType) {
3714 accessChainStore(type, rValue);
3715 return;
3716 }
3717
John Kessenichb3e24e42016-09-11 12:33:43 -06003718 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003719 // where the two types were the same type in GLSL. This requires member
3720 // by member copy, recursively.
3721
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003722 // SPIR-V 1.4 added an instruction to do help do this.
3723 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3724 // However, bool in uniform space is changed to int, so
3725 // OpCopyLogical does not work for that.
3726 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3727 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3728 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3729 if (lBool == rBool) {
3730 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3731 accessChainStore(type, logicalCopy);
3732 return;
3733 }
3734 }
3735
John Kessenichb3e24e42016-09-11 12:33:43 -06003736 // If an array, copy element by element.
3737 if (type.isArray()) {
3738 glslang::TType glslangElementType(type, 0);
3739 spv::Id elementRType = builder.getContainedTypeId(rType);
3740 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3741 // get the source member
3742 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003743
John Kessenichb3e24e42016-09-11 12:33:43 -06003744 // set up the target storage
3745 builder.clearAccessChain();
3746 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003747 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003748
John Kessenichb3e24e42016-09-11 12:33:43 -06003749 // store the member
3750 multiTypeStore(glslangElementType, elementRValue);
3751 }
3752 } else {
3753 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003754
John Kessenichb3e24e42016-09-11 12:33:43 -06003755 // loop over structure members
3756 const glslang::TTypeList& members = *type.getStruct();
3757 for (int m = 0; m < (int)members.size(); ++m) {
3758 const glslang::TType& glslangMemberType = *members[m].type;
3759
3760 // get the source member
3761 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3762 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3763
3764 // set up the target storage
3765 builder.clearAccessChain();
3766 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003767 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003768
3769 // store the member
3770 multiTypeStore(glslangMemberType, memberRValue);
3771 }
John Kessenich4bf71552016-09-02 11:20:21 -06003772 }
3773}
3774
John Kessenichf85e8062015-12-19 13:57:10 -07003775// Decide whether or not this type should be
3776// decorated with offsets and strides, and if so
3777// whether std140 or std430 rules should be applied.
3778glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003779{
John Kessenichf85e8062015-12-19 13:57:10 -07003780 // has to be a block
3781 if (type.getBasicType() != glslang::EbtBlock)
3782 return glslang::ElpNone;
3783
Chao Chen3c366992018-09-19 11:41:59 -07003784 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003785 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003786 type.getQualifier().storage != glslang::EvqBuffer &&
3787 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003788 return glslang::ElpNone;
3789
3790 // return the layout to use
3791 switch (type.getQualifier().layoutPacking) {
3792 case glslang::ElpStd140:
3793 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003794 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003795 return type.getQualifier().layoutPacking;
3796 default:
3797 return glslang::ElpNone;
3798 }
John Kessenich31ed4832015-09-09 17:51:38 -06003799}
3800
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003801// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003802int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003803{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003804 int size;
John Kessenich49987892015-12-29 17:11:44 -07003805 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003806 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003807
3808 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003809}
3810
John Kessenich49987892015-12-29 17:11:44 -07003811// 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 -07003812// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003813int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003814{
John Kessenich49987892015-12-29 17:11:44 -07003815 glslang::TType elementType;
3816 elementType.shallowCopy(matrixType);
3817 elementType.clearArraySizes();
3818
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003819 int size;
John Kessenich49987892015-12-29 17:11:44 -07003820 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003821 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003822
3823 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003824}
3825
John Kessenich5e4b1242015-08-06 22:53:06 -06003826// Given a member type of a struct, realign the current offset for it, and compute
3827// the next (not yet aligned) offset for the next member, which will get aligned
3828// on the next call.
3829// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3830// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3831// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003832void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003833 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003834{
3835 // this will get a positive value when deemed necessary
3836 nextOffset = -1;
3837
John Kessenich5e4b1242015-08-06 22:53:06 -06003838 // override anything in currentOffset with user-set offset
3839 if (memberType.getQualifier().hasOffset())
3840 currentOffset = memberType.getQualifier().layoutOffset;
3841
3842 // It could be that current linker usage in glslang updated all the layoutOffset,
3843 // in which case the following code does not matter. But, that's not quite right
3844 // once cross-compilation unit GLSL validation is done, as the original user
3845 // settings are needed in layoutOffset, and then the following will come into play.
3846
John Kessenichf85e8062015-12-19 13:57:10 -07003847 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003848 if (! memberType.getQualifier().hasOffset())
3849 currentOffset = -1;
3850
3851 return;
3852 }
3853
John Kessenichf85e8062015-12-19 13:57:10 -07003854 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 if (currentOffset < 0)
3856 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003857
John Kessenich5e4b1242015-08-06 22:53:06 -06003858 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3859 // but possibly not yet correctly aligned.
3860
3861 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003862 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003863 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003864
3865 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003866 // TODO: make this consistent in early phases of code:
3867 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3868 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3869 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003870 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003871 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003872 int dummySize;
3873 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3874 if (componentAlignment <= 4)
3875 memberAlignment = componentAlignment;
3876 }
3877
3878 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003879 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003880
3881 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003882 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003883 glslang::RoundToPow2(currentOffset, 16);
3884
John Kessenich5e4b1242015-08-06 22:53:06 -06003885 nextOffset = currentOffset + memberSize;
3886}
3887
David Netoa901ffe2016-06-08 14:11:40 +01003888void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003889{
David Netoa901ffe2016-06-08 14:11:40 +01003890 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3891 switch (glslangBuiltIn)
3892 {
3893 case glslang::EbvClipDistance:
3894 case glslang::EbvCullDistance:
3895 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003896#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003897 case glslang::EbvViewportMaskNV:
3898 case glslang::EbvSecondaryPositionNV:
3899 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003900 case glslang::EbvPositionPerViewNV:
3901 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003902 case glslang::EbvTaskCountNV:
3903 case glslang::EbvPrimitiveCountNV:
3904 case glslang::EbvPrimitiveIndicesNV:
3905 case glslang::EbvClipDistancePerViewNV:
3906 case glslang::EbvCullDistancePerViewNV:
3907 case glslang::EbvLayerPerViewNV:
3908 case glslang::EbvMeshViewCountNV:
3909 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003910#endif
David Netoa901ffe2016-06-08 14:11:40 +01003911 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3912 // Alternately, we could just call this for any glslang built-in, since the
3913 // capability already guards against duplicates.
3914 TranslateBuiltInDecoration(glslangBuiltIn, false);
3915 break;
3916 default:
3917 // Capabilities were already generated when the struct was declared.
3918 break;
3919 }
John Kessenichebb50532016-05-16 19:22:05 -06003920}
3921
John Kessenich6fccb3c2016-09-19 16:01:41 -06003922bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003923{
John Kessenicheee9d532016-09-19 18:09:30 -06003924 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003925}
3926
John Kessenichd41993d2017-09-10 15:21:05 -06003927// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003928// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3929// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003930bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003931{
John Kessenich6a14f782017-12-04 02:48:10 -07003932 assert(qualifier == glslang::EvqIn ||
3933 qualifier == glslang::EvqOut ||
3934 qualifier == glslang::EvqInOut ||
3935 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003936 return qualifier != glslang::EvqConstReadOnly;
3937}
3938
3939// Is parameter pass-by-original?
3940bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3941 bool implicitThisParam)
3942{
3943 if (implicitThisParam) // implicit this
3944 return true;
3945 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003946 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003947 return paramType.containsOpaque() || // sampler, etc.
3948 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3949}
3950
John Kessenich140f3df2015-06-26 16:58:36 -06003951// Make all the functions, skeletally, without actually visiting their bodies.
3952void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3953{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003954 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003955 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3956 if (paramPrecision != spv::NoPrecision)
3957 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003958 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003959 if (type.getBasicType() == glslang::EbtReference) {
3960 // Original and non-writable params pass the pointer directly and
3961 // use restrict/aliased, others are stored to a pointer in Function
3962 // memory and use RestrictPointer/AliasedPointer.
3963 if (originalParam(type.getQualifier().storage, type, false) ||
3964 !writableParam(type.getQualifier().storage)) {
3965 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3966 } else {
3967 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3968 }
3969 }
John Kessenichfad62972017-07-18 02:35:46 -06003970 };
3971
John Kessenich140f3df2015-06-26 16:58:36 -06003972 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3973 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003974 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003975 continue;
3976
3977 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003978 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003979 //
qining25262b32016-05-06 17:25:16 -04003980 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003981 // function. What it is an address of varies:
3982 //
John Kessenich4bf71552016-09-02 11:20:21 -06003983 // - "in" parameters not marked as "const" can be written to without modifying the calling
3984 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003985 //
3986 // - "const in" parameters can just be the r-value, as no writes need occur.
3987 //
John Kessenich4bf71552016-09-02 11:20:21 -06003988 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3989 // 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 -06003990
3991 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003992 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003993 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3994
John Kessenichfad62972017-07-18 02:35:46 -06003995 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3996 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003997
John Kessenichfad62972017-07-18 02:35:46 -06003998 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003999 for (int p = 0; p < (int)parameters.size(); ++p) {
4000 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4001 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004002 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004003 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004004 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004005 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4006 else
John Kessenich4bf71552016-09-02 11:20:21 -06004007 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004008 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004009 paramTypes.push_back(typeId);
4010 }
4011
4012 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004013 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4014 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004015 glslFunction->getName().c_str(), paramTypes,
4016 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004017 if (implicitThis)
4018 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004019
4020 // Track function to emit/call later
4021 functionMap[glslFunction->getName().c_str()] = function;
4022
4023 // Set the parameter id's
4024 for (int p = 0; p < (int)parameters.size(); ++p) {
4025 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4026 // give a name too
4027 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
4028 }
4029 }
4030}
4031
4032// Process all the initializers, while skipping the functions and link objects
4033void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4034{
4035 builder.setBuildPoint(shaderEntry->getLastBlock());
4036 for (int i = 0; i < (int)initializers.size(); ++i) {
4037 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4038 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4039
4040 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004041 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004042 initializer->traverse(this);
4043 }
4044 }
4045}
4046
4047// Process all the functions, while skipping initializers.
4048void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4049{
4050 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4051 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004052 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004053 node->traverse(this);
4054 }
4055}
4056
4057void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4058{
qining25262b32016-05-06 17:25:16 -04004059 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004060 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004061 currentFunction = functionMap[node->getName().c_str()];
4062 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004063 builder.setBuildPoint(functionBlock);
4064}
4065
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004066void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004067{
Rex Xufc618912015-09-09 16:42:49 +08004068 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004069
4070 glslang::TSampler sampler = {};
4071 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004072#ifdef AMD_EXTENSIONS
4073 bool f16ShadowCompare = false;
4074#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004075 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004076 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4077 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004078#ifdef AMD_EXTENSIONS
4079 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4080#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004081 }
4082
John Kessenich140f3df2015-06-26 16:58:36 -06004083 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4084 builder.clearAccessChain();
4085 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004086
4087 // Special case l-value operands
4088 bool lvalue = false;
4089 switch (node.getOp()) {
4090 case glslang::EOpImageAtomicAdd:
4091 case glslang::EOpImageAtomicMin:
4092 case glslang::EOpImageAtomicMax:
4093 case glslang::EOpImageAtomicAnd:
4094 case glslang::EOpImageAtomicOr:
4095 case glslang::EOpImageAtomicXor:
4096 case glslang::EOpImageAtomicExchange:
4097 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004098 case glslang::EOpImageAtomicLoad:
4099 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004100 if (i == 0)
4101 lvalue = true;
4102 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004103 case glslang::EOpSparseImageLoad:
4104 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4105 lvalue = true;
4106 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004107#ifdef AMD_EXTENSIONS
4108 case glslang::EOpSparseTexture:
4109 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4110 lvalue = true;
4111 break;
4112 case glslang::EOpSparseTextureClamp:
4113 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4114 lvalue = true;
4115 break;
4116 case glslang::EOpSparseTextureLod:
4117 case glslang::EOpSparseTextureOffset:
4118 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4119 lvalue = true;
4120 break;
4121#else
Rex Xu48edadf2015-12-31 16:11:41 +08004122 case glslang::EOpSparseTexture:
4123 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4124 lvalue = true;
4125 break;
4126 case glslang::EOpSparseTextureClamp:
4127 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4128 lvalue = true;
4129 break;
4130 case glslang::EOpSparseTextureLod:
4131 case glslang::EOpSparseTextureOffset:
4132 if (i == 3)
4133 lvalue = true;
4134 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004135#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004136 case glslang::EOpSparseTextureFetch:
4137 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4138 lvalue = true;
4139 break;
4140 case glslang::EOpSparseTextureFetchOffset:
4141 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4142 lvalue = true;
4143 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004144#ifdef AMD_EXTENSIONS
4145 case glslang::EOpSparseTextureLodOffset:
4146 case glslang::EOpSparseTextureGrad:
4147 case glslang::EOpSparseTextureOffsetClamp:
4148 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4149 lvalue = true;
4150 break;
4151 case glslang::EOpSparseTextureGradOffset:
4152 case glslang::EOpSparseTextureGradClamp:
4153 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4154 lvalue = true;
4155 break;
4156 case glslang::EOpSparseTextureGradOffsetClamp:
4157 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4158 lvalue = true;
4159 break;
4160#else
Rex Xu48edadf2015-12-31 16:11:41 +08004161 case glslang::EOpSparseTextureLodOffset:
4162 case glslang::EOpSparseTextureGrad:
4163 case glslang::EOpSparseTextureOffsetClamp:
4164 if (i == 4)
4165 lvalue = true;
4166 break;
4167 case glslang::EOpSparseTextureGradOffset:
4168 case glslang::EOpSparseTextureGradClamp:
4169 if (i == 5)
4170 lvalue = true;
4171 break;
4172 case glslang::EOpSparseTextureGradOffsetClamp:
4173 if (i == 6)
4174 lvalue = true;
4175 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004176#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004177 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004178 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4179 lvalue = true;
4180 break;
4181 case glslang::EOpSparseTextureGatherOffset:
4182 case glslang::EOpSparseTextureGatherOffsets:
4183 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4184 lvalue = true;
4185 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004186#ifdef AMD_EXTENSIONS
4187 case glslang::EOpSparseTextureGatherLod:
4188 if (i == 3)
4189 lvalue = true;
4190 break;
4191 case glslang::EOpSparseTextureGatherLodOffset:
4192 case glslang::EOpSparseTextureGatherLodOffsets:
4193 if (i == 4)
4194 lvalue = true;
4195 break;
Rex Xu129799a2017-07-05 17:23:28 +08004196 case glslang::EOpSparseImageLoadLod:
4197 if (i == 3)
4198 lvalue = true;
4199 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004200#endif
Chao Chen3a137962018-09-19 11:41:27 -07004201#ifdef NV_EXTENSIONS
4202 case glslang::EOpImageSampleFootprintNV:
4203 if (i == 4)
4204 lvalue = true;
4205 break;
4206 case glslang::EOpImageSampleFootprintClampNV:
4207 case glslang::EOpImageSampleFootprintLodNV:
4208 if (i == 5)
4209 lvalue = true;
4210 break;
4211 case glslang::EOpImageSampleFootprintGradNV:
4212 if (i == 6)
4213 lvalue = true;
4214 break;
4215 case glslang::EOpImageSampleFootprintGradClampNV:
4216 if (i == 7)
4217 lvalue = true;
4218 break;
4219#endif
Rex Xufc618912015-09-09 16:42:49 +08004220 default:
4221 break;
4222 }
4223
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004224 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004225 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004226 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4227 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4228 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004229 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004230 }
4231}
4232
John Kessenichfc51d282015-08-19 13:34:18 -06004233void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004234{
John Kessenichfc51d282015-08-19 13:34:18 -06004235 builder.clearAccessChain();
4236 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004237 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004238}
John Kessenich140f3df2015-06-26 16:58:36 -06004239
John Kessenichfc51d282015-08-19 13:34:18 -06004240spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4241{
John Kesseniche485c7a2017-05-31 18:50:53 -06004242 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004243 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004244
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004245 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004246
John Kessenichfc51d282015-08-19 13:34:18 -06004247 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004248
John Kessenichf43c7392019-03-31 10:51:57 -06004249 const glslang::TType &imageType = node->getAsAggregate()
4250 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4251 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004252 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004253#ifdef AMD_EXTENSIONS
4254 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004255 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4256 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004257#endif
4258
John Kessenichf43c7392019-03-31 10:51:57 -06004259 const auto signExtensionMask = [&]() {
4260 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4261 if (sampler.type == glslang::EbtUint)
4262 return spv::ImageOperandsZeroExtendMask;
4263 else if (sampler.type == glslang::EbtInt)
4264 return spv::ImageOperandsSignExtendMask;
4265 }
4266 return spv::ImageOperandsMaskNone;
4267 };
4268
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004269 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4270
John Kessenichfc51d282015-08-19 13:34:18 -06004271 std::vector<spv::Id> arguments;
4272 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004273 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004274 else
4275 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004276 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004277
4278 spv::Builder::TextureParameters params = { };
4279 params.sampler = arguments[0];
4280
Rex Xu04db3f52015-09-16 11:44:02 +08004281 glslang::TCrackedTextureOp cracked;
4282 node->crackTexture(sampler, cracked);
4283
amhagan05506bb2017-06-13 16:53:02 -04004284 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004285
John Kessenichfc51d282015-08-19 13:34:18 -06004286 // Check for queries
4287 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004288 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4289 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004290 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004291
John Kessenichfc51d282015-08-19 13:34:18 -06004292 switch (node->getOp()) {
4293 case glslang::EOpImageQuerySize:
4294 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004295 if (arguments.size() > 1) {
4296 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004297 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004298 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004299 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004300 case glslang::EOpImageQuerySamples:
4301 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004302 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004303 case glslang::EOpTextureQueryLod:
4304 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004305 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004306 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004307 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004308 case glslang::EOpSparseTexelsResident:
4309 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004310 default:
4311 assert(0);
4312 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004313 }
John Kessenich140f3df2015-06-26 16:58:36 -06004314 }
4315
LoopDawg4425f242018-02-18 11:40:01 -07004316 int components = node->getType().getVectorSize();
4317
4318 if (node->getOp() == glslang::EOpTextureFetch) {
4319 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4320 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4321 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4322 // here around e.g. which ones return scalars or other types.
4323 components = 4;
4324 }
4325
4326 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4327
4328 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4329
Rex Xufc618912015-09-09 16:42:49 +08004330 // Check for image functions other than queries
4331 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004332 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004333 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004334 spv::IdImmediate image = { true, *(opIt++) };
4335 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004336
4337 // Handle subpass operations
4338 // TODO: GLSL should change to have the "MS" only on the type rather than the
4339 // built-in function.
4340 if (cracked.subpass) {
4341 // add on the (0,0) coordinate
4342 spv::Id zero = builder.makeIntConstant(0);
4343 std::vector<spv::Id> comps;
4344 comps.push_back(zero);
4345 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004346 spv::IdImmediate coord = { true,
4347 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4348 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004349 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4350 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004351 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004352 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4353 }
4354 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004355 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004356 if (sampler.ms) {
4357 spv::IdImmediate imageOperand = { true, *(opIt++) };
4358 operands.push_back(imageOperand);
4359 }
John Kessenich6c292d32016-02-15 20:58:50 -07004360 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004361 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4362 builder.setPrecision(result, precision);
4363 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004364 }
4365
John Kessenich149afc32018-08-14 13:31:43 -06004366 spv::IdImmediate coord = { true, *(opIt++) };
4367 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004368#ifdef AMD_EXTENSIONS
4369 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4370#else
John Kessenich56bab042015-09-16 10:54:31 -06004371 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004372#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004373 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004374 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004375 mask = mask | spv::ImageOperandsSampleMask;
4376 }
Rex Xu129799a2017-07-05 17:23:28 +08004377#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004378 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004379 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4380 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004381 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004382 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004383#endif
4384 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4385 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004386 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004387 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004388 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4389 operands.push_back(imageOperands);
4390 }
4391 if (mask & spv::ImageOperandsSampleMask) {
4392 spv::IdImmediate imageOperand = { true, *opIt++ };
4393 operands.push_back(imageOperand);
4394 }
4395#ifdef AMD_EXTENSIONS
4396 if (mask & spv::ImageOperandsLodMask) {
4397 spv::IdImmediate imageOperand = { true, *opIt++ };
4398 operands.push_back(imageOperand);
4399 }
4400#endif
4401 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004402 spv::IdImmediate imageOperand = { true,
4403 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004404 operands.push_back(imageOperand);
4405 }
4406
John Kessenich149afc32018-08-14 13:31:43 -06004407 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004408 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004409
John Kessenich149afc32018-08-14 13:31:43 -06004410 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004411 builder.setPrecision(result[0], precision);
4412
4413 // If needed, add a conversion constructor to the proper size.
4414 if (components != node->getType().getVectorSize())
4415 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4416
4417 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004418#ifdef AMD_EXTENSIONS
4419 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4420#else
John Kessenich56bab042015-09-16 10:54:31 -06004421 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004422#endif
Rex Xu129799a2017-07-05 17:23:28 +08004423
Jeff Bolz36831c92018-09-05 10:11:41 -05004424 // Push the texel value before the operands
4425#ifdef AMD_EXTENSIONS
4426 if (sampler.ms || cracked.lod) {
4427#else
4428 if (sampler.ms) {
4429#endif
John Kessenich149afc32018-08-14 13:31:43 -06004430 spv::IdImmediate texel = { true, *(opIt + 1) };
4431 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004432 } else {
4433 spv::IdImmediate texel = { true, *opIt };
4434 operands.push_back(texel);
4435 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004436
4437 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4438 if (sampler.ms) {
4439 mask = mask | spv::ImageOperandsSampleMask;
4440 }
4441#ifdef AMD_EXTENSIONS
4442 if (cracked.lod) {
4443 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4444 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4445 mask = mask | spv::ImageOperandsLodMask;
4446 }
4447#endif
4448 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4449 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004450 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004451 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004452 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4453 operands.push_back(imageOperands);
4454 }
4455 if (mask & spv::ImageOperandsSampleMask) {
4456 spv::IdImmediate imageOperand = { true, *opIt++ };
4457 operands.push_back(imageOperand);
4458 }
4459#ifdef AMD_EXTENSIONS
4460 if (mask & spv::ImageOperandsLodMask) {
4461 spv::IdImmediate imageOperand = { true, *opIt++ };
4462 operands.push_back(imageOperand);
4463 }
4464#endif
4465 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004466 spv::IdImmediate imageOperand = { true,
4467 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004468 operands.push_back(imageOperand);
4469 }
4470
John Kessenich56bab042015-09-16 10:54:31 -06004471 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004472 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004473 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004474 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004475#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004476 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4477 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004478#else
Rex Xu5eafa472016-02-19 22:24:03 +08004479 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004480#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004481 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004482 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004483 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4484
Jeff Bolz36831c92018-09-05 10:11:41 -05004485 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004486 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004487 mask = mask | spv::ImageOperandsSampleMask;
4488 }
Rex Xu129799a2017-07-05 17:23:28 +08004489#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004490 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004491 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4492 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4493
Jeff Bolz36831c92018-09-05 10:11:41 -05004494 mask = mask | spv::ImageOperandsLodMask;
4495 }
4496#endif
4497 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4498 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004499 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004500 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004501 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004502 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004503 }
4504 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004505 spv::IdImmediate imageOperand = { true, *opIt++ };
4506 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004507 }
4508#ifdef AMD_EXTENSIONS
4509 if (mask & spv::ImageOperandsLodMask) {
4510 spv::IdImmediate imageOperand = { true, *opIt++ };
4511 operands.push_back(imageOperand);
4512 }
Rex Xu129799a2017-07-05 17:23:28 +08004513#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004514 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4515 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4516 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004517 }
4518
4519 // Create the return type that was a special structure
4520 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004521 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004522 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4523 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4524
4525 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4526
4527 // Decode the return type
4528 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4529 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004530 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004531 // Process image atomic operations
4532
4533 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4534 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004535 // For non-MS, the sample value should be 0
4536 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4537 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004538
Jeff Bolz36831c92018-09-05 10:11:41 -05004539 spv::Id resultTypeId;
4540 // imageAtomicStore has a void return type so base the pointer type on
4541 // the type of the value operand.
4542 if (node->getOp() == glslang::EOpImageAtomicStore) {
4543 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4544 } else {
4545 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4546 }
John Kessenich56bab042015-09-16 10:54:31 -06004547 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004548
4549 std::vector<spv::Id> operands;
4550 operands.push_back(pointer);
4551 for (; opIt != arguments.end(); ++opIt)
4552 operands.push_back(*opIt);
4553
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004554 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004555 }
4556 }
4557
amhagan05506bb2017-06-13 16:53:02 -04004558#ifdef AMD_EXTENSIONS
4559 // Check for fragment mask functions other than queries
4560 if (cracked.fragMask) {
4561 assert(sampler.ms);
4562
4563 auto opIt = arguments.begin();
4564 std::vector<spv::Id> operands;
4565
4566 // Extract the image if necessary
4567 if (builder.isSampledImage(params.sampler))
4568 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4569
4570 operands.push_back(params.sampler);
4571 ++opIt;
4572
4573 if (sampler.isSubpass()) {
4574 // add on the (0,0) coordinate
4575 spv::Id zero = builder.makeIntConstant(0);
4576 std::vector<spv::Id> comps;
4577 comps.push_back(zero);
4578 comps.push_back(zero);
4579 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4580 }
4581
4582 for (; opIt != arguments.end(); ++opIt)
4583 operands.push_back(*opIt);
4584
4585 spv::Op fragMaskOp = spv::OpNop;
4586 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4587 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4588 else if (node->getOp() == glslang::EOpFragmentFetch)
4589 fragMaskOp = spv::OpFragmentFetchAMD;
4590
4591 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4592 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4593 return builder.createOp(fragMaskOp, resultType(), operands);
4594 }
4595#endif
4596
Rex Xufc618912015-09-09 16:42:49 +08004597 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004598 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004599#ifdef NV_EXTENSIONS
4600 bool imageFootprint = node->isImageFootprint();
4601#endif
4602
Rex Xu71519fe2015-11-11 15:35:47 +08004603 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4604
John Kessenichfc51d282015-08-19 13:34:18 -06004605 // check for bias argument
4606 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004607#ifdef AMD_EXTENSIONS
4608 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4609#else
Rex Xu71519fe2015-11-11 15:35:47 +08004610 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004611#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004612 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004613#ifdef AMD_EXTENSIONS
4614 if (cracked.gather)
4615 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004616
4617 if (f16ShadowCompare)
4618 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004619#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004620 if (cracked.offset)
4621 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004622#ifdef AMD_EXTENSIONS
4623 else if (cracked.offsets)
4624 ++nonBiasArgCount;
4625#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004626 if (cracked.grad)
4627 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004628 if (cracked.lodClamp)
4629 ++nonBiasArgCount;
4630 if (sparse)
4631 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004632#ifdef NV_EXTENSIONS
4633 if (imageFootprint)
4634 //Following three extra arguments
4635 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4636 nonBiasArgCount += 3;
4637#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004638 if ((int)arguments.size() > nonBiasArgCount)
4639 bias = true;
4640 }
4641
John Kessenicha5c33d62016-06-02 23:45:21 -06004642 // See if the sampler param should really be just the SPV image part
4643 if (cracked.fetch) {
4644 // a fetch needs to have the image extracted first
4645 if (builder.isSampledImage(params.sampler))
4646 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4647 }
4648
Rex Xu225e0fc2016-11-17 17:47:59 +08004649#ifdef AMD_EXTENSIONS
4650 if (cracked.gather) {
4651 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4652 if (bias || cracked.lod ||
4653 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4654 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004655 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004656 }
4657 }
4658#endif
4659
John Kessenichfc51d282015-08-19 13:34:18 -06004660 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004661
John Kessenichfc51d282015-08-19 13:34:18 -06004662 params.coords = arguments[1];
4663 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004664 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004665
4666 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004667#ifdef AMD_EXTENSIONS
4668 if (cubeCompare || f16ShadowCompare) {
4669#else
Rex Xu48edadf2015-12-31 16:11:41 +08004670 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004671#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004672 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004673 ++extraArgs;
4674 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004675 params.Dref = arguments[2];
4676 ++extraArgs;
4677 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004678 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004679 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004680 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004681 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004682 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004683 dRefComp = builder.getNumComponents(params.coords) - 1;
4684 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004685 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4686 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004687
4688 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004689 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004690 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004691 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004692 } else if (glslangIntermediate->getStage() != EShLangFragment
4693#ifdef NV_EXTENSIONS
4694 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4695 && !(glslangIntermediate->getStage() == EShLangCompute &&
4696 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4697#endif
4698 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004699 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4700 noImplicitLod = true;
4701 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004702
4703 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004704 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004705 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004706 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004707 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004708
4709 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004710 if (cracked.grad) {
4711 params.gradX = arguments[2 + extraArgs];
4712 params.gradY = arguments[3 + extraArgs];
4713 extraArgs += 2;
4714 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004715
4716 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004717 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004718 params.offset = arguments[2 + extraArgs];
4719 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004720 } else if (cracked.offsets) {
4721 params.offsets = arguments[2 + extraArgs];
4722 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004723 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004724
4725 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004726 if (cracked.lodClamp) {
4727 params.lodClamp = arguments[2 + extraArgs];
4728 ++extraArgs;
4729 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004730 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004731 if (sparse) {
4732 params.texelOut = arguments[2 + extraArgs];
4733 ++extraArgs;
4734 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004735
John Kessenich76d4dfc2016-06-16 12:43:23 -06004736 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004737 if (cracked.gather && ! sampler.shadow) {
4738 // default component is 0, if missing, otherwise an argument
4739 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004740 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004741 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004742 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004743 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004744 }
Chao Chen3a137962018-09-19 11:41:27 -07004745#ifdef NV_EXTENSIONS
4746 spv::Id resultStruct = spv::NoResult;
4747 if (imageFootprint) {
4748 //Following three extra arguments
4749 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4750 params.granularity = arguments[2 + extraArgs];
4751 params.coarse = arguments[3 + extraArgs];
4752 resultStruct = arguments[4 + extraArgs];
4753 extraArgs += 3;
4754 }
4755#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004756 // bias
4757 if (bias) {
4758 params.bias = arguments[2 + extraArgs];
4759 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004760 }
John Kessenichfc51d282015-08-19 13:34:18 -06004761
Chao Chen3a137962018-09-19 11:41:27 -07004762#ifdef NV_EXTENSIONS
4763 if (imageFootprint) {
4764 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4765 builder.addCapability(spv::CapabilityImageFootprintNV);
4766
4767
4768 //resultStructType(OpenGL type) contains 5 elements:
4769 //struct gl_TextureFootprint2DNV {
4770 // uvec2 anchor;
4771 // uvec2 offset;
4772 // uvec2 mask;
4773 // uint lod;
4774 // uint granularity;
4775 //};
4776 //or
4777 //struct gl_TextureFootprint3DNV {
4778 // uvec3 anchor;
4779 // uvec3 offset;
4780 // uvec2 mask;
4781 // uint lod;
4782 // uint granularity;
4783 //};
4784 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4785 assert(builder.isStructType(resultStructType));
4786
4787 //resType (SPIR-V type) contains 6 elements:
4788 //Member 0 must be a Boolean type scalar(LOD),
4789 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4790 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4791 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4792 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4793 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4794 std::vector<spv::Id> members;
4795 members.push_back(resultType());
4796 for (int i = 0; i < 5; i++) {
4797 members.push_back(builder.getContainedTypeId(resultStructType, i));
4798 }
4799 spv::Id resType = builder.makeStructType(members, "ResType");
4800
4801 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004802 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4803 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004804
4805 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4806 for (int i = 0; i < 5; i++) {
4807 builder.clearAccessChain();
4808 builder.setAccessChainLValue(resultStruct);
4809
4810 //Accessing to a struct we created, no coherent flag is set
4811 spv::Builder::AccessChain::CoherentFlags flags;
4812 flags.clear();
4813
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004814 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004815 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4816 }
4817 return builder.createCompositeExtract(res, resultType(), 0);
4818 }
4819#endif
4820
John Kessenich65336482016-06-16 14:06:26 -06004821 // projective component (might not to move)
4822 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4823 // are divided by the last component of P."
4824 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4825 // unused components will appear after all used components."
4826 if (cracked.proj) {
4827 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4828 int projTargetComp;
4829 switch (sampler.dim) {
4830 case glslang::Esd1D: projTargetComp = 1; break;
4831 case glslang::Esd2D: projTargetComp = 2; break;
4832 case glslang::EsdRect: projTargetComp = 2; break;
4833 default: projTargetComp = projSourceComp; break;
4834 }
4835 // copy the projective coordinate if we have to
4836 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004837 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004838 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4839 projSourceComp);
4840 params.coords = builder.createCompositeInsert(projComp, params.coords,
4841 builder.getTypeId(params.coords), projTargetComp);
4842 }
4843 }
4844
Jeff Bolz36831c92018-09-05 10:11:41 -05004845 // nonprivate
4846 if (imageType.getQualifier().nonprivate) {
4847 params.nonprivate = true;
4848 }
4849
4850 // volatile
4851 if (imageType.getQualifier().volatil) {
4852 params.volatil = true;
4853 }
4854
St0fFa1184dd2018-04-09 21:08:14 +02004855 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004856 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4857 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004858 );
LoopDawg4425f242018-02-18 11:40:01 -07004859
4860 if (components != node->getType().getVectorSize())
4861 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4862
4863 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004864}
4865
4866spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4867{
4868 // Grab the function's pointer from the previously created function
4869 spv::Function* function = functionMap[node->getName().c_str()];
4870 if (! function)
4871 return 0;
4872
4873 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4874 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4875
4876 // See comments in makeFunctions() for details about the semantics for parameter passing.
4877 //
4878 // These imply we need a four step process:
4879 // 1. Evaluate the arguments
4880 // 2. Allocate and make copies of in, out, and inout arguments
4881 // 3. Make the call
4882 // 4. Copy back the results
4883
John Kessenichd3ed90b2018-05-04 11:43:03 -06004884 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004885 std::vector<spv::Builder::AccessChain> lValues;
4886 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004887 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004888 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004889 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004890 // build l-value
4891 builder.clearAccessChain();
4892 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004893 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004894 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004895 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004896 // save l-value
4897 lValues.push_back(builder.getAccessChain());
4898 } else {
4899 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004900 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004901 }
4902 }
4903
4904 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4905 // copy the original into that space.
4906 //
4907 // Also, build up the list of actual arguments to pass in for the call
4908 int lValueCount = 0;
4909 int rValueCount = 0;
4910 std::vector<spv::Id> spvArgs;
4911 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4912 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004913 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004914 builder.setAccessChain(lValues[lValueCount]);
4915 arg = builder.accessChainGetLValue();
4916 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004917 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004918 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004919 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004920 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4921 // need to copy the input into output space
4922 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004923 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004924 builder.clearAccessChain();
4925 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004926 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004927 }
4928 ++lValueCount;
4929 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004930 // process r-value, which involves a copy for a type mismatch
4931 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4932 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4933 builder.clearAccessChain();
4934 builder.setAccessChainLValue(argCopy);
4935 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4936 arg = builder.createLoad(argCopy);
4937 } else
4938 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004939 ++rValueCount;
4940 }
4941 spvArgs.push_back(arg);
4942 }
4943
4944 // 3. Make the call.
4945 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004946 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004947
4948 // 4. Copy back out an "out" arguments.
4949 lValueCount = 0;
4950 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004951 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004952 ++lValueCount;
4953 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004954 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4955 spv::Id copy = builder.createLoad(spvArgs[a]);
4956 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004957 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004958 }
4959 ++lValueCount;
4960 }
4961 }
4962
4963 return result;
4964}
4965
4966// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004967spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004968 spv::Id typeId, spv::Id left, spv::Id right,
4969 glslang::TBasicType typeProxy, bool reduceComparison)
4970{
John Kessenich66011cb2018-03-06 16:12:04 -07004971 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4972 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004973 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004974
4975 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004976 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004977 bool comparison = false;
4978
4979 switch (op) {
4980 case glslang::EOpAdd:
4981 case glslang::EOpAddAssign:
4982 if (isFloat)
4983 binOp = spv::OpFAdd;
4984 else
4985 binOp = spv::OpIAdd;
4986 break;
4987 case glslang::EOpSub:
4988 case glslang::EOpSubAssign:
4989 if (isFloat)
4990 binOp = spv::OpFSub;
4991 else
4992 binOp = spv::OpISub;
4993 break;
4994 case glslang::EOpMul:
4995 case glslang::EOpMulAssign:
4996 if (isFloat)
4997 binOp = spv::OpFMul;
4998 else
4999 binOp = spv::OpIMul;
5000 break;
5001 case glslang::EOpVectorTimesScalar:
5002 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005003 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005004 if (builder.isVector(right))
5005 std::swap(left, right);
5006 assert(builder.isScalar(right));
5007 needMatchingVectors = false;
5008 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005009 } else if (isFloat)
5010 binOp = spv::OpFMul;
5011 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005012 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005013 break;
5014 case glslang::EOpVectorTimesMatrix:
5015 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005016 binOp = spv::OpVectorTimesMatrix;
5017 break;
5018 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005019 binOp = spv::OpMatrixTimesVector;
5020 break;
5021 case glslang::EOpMatrixTimesScalar:
5022 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005023 binOp = spv::OpMatrixTimesScalar;
5024 break;
5025 case glslang::EOpMatrixTimesMatrix:
5026 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005027 binOp = spv::OpMatrixTimesMatrix;
5028 break;
5029 case glslang::EOpOuterProduct:
5030 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005031 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 break;
5033
5034 case glslang::EOpDiv:
5035 case glslang::EOpDivAssign:
5036 if (isFloat)
5037 binOp = spv::OpFDiv;
5038 else if (isUnsigned)
5039 binOp = spv::OpUDiv;
5040 else
5041 binOp = spv::OpSDiv;
5042 break;
5043 case glslang::EOpMod:
5044 case glslang::EOpModAssign:
5045 if (isFloat)
5046 binOp = spv::OpFMod;
5047 else if (isUnsigned)
5048 binOp = spv::OpUMod;
5049 else
5050 binOp = spv::OpSMod;
5051 break;
5052 case glslang::EOpRightShift:
5053 case glslang::EOpRightShiftAssign:
5054 if (isUnsigned)
5055 binOp = spv::OpShiftRightLogical;
5056 else
5057 binOp = spv::OpShiftRightArithmetic;
5058 break;
5059 case glslang::EOpLeftShift:
5060 case glslang::EOpLeftShiftAssign:
5061 binOp = spv::OpShiftLeftLogical;
5062 break;
5063 case glslang::EOpAnd:
5064 case glslang::EOpAndAssign:
5065 binOp = spv::OpBitwiseAnd;
5066 break;
5067 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005068 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005069 binOp = spv::OpLogicalAnd;
5070 break;
5071 case glslang::EOpInclusiveOr:
5072 case glslang::EOpInclusiveOrAssign:
5073 binOp = spv::OpBitwiseOr;
5074 break;
5075 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005076 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005077 binOp = spv::OpLogicalOr;
5078 break;
5079 case glslang::EOpExclusiveOr:
5080 case glslang::EOpExclusiveOrAssign:
5081 binOp = spv::OpBitwiseXor;
5082 break;
5083 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005084 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005085 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005086 break;
5087
5088 case glslang::EOpLessThan:
5089 case glslang::EOpGreaterThan:
5090 case glslang::EOpLessThanEqual:
5091 case glslang::EOpGreaterThanEqual:
5092 case glslang::EOpEqual:
5093 case glslang::EOpNotEqual:
5094 case glslang::EOpVectorEqual:
5095 case glslang::EOpVectorNotEqual:
5096 comparison = true;
5097 break;
5098 default:
5099 break;
5100 }
5101
John Kessenich7c1aa102015-10-15 13:29:11 -06005102 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005103 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005104 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005105 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5106 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005107 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005108
5109 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005110 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005111 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005112
qining25262b32016-05-06 17:25:16 -04005113 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005114 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005115 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005116 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005117 }
5118
5119 if (! comparison)
5120 return 0;
5121
John Kessenich7c1aa102015-10-15 13:29:11 -06005122 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005123
John Kessenich4583b612016-08-07 19:14:22 -06005124 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005125 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5126 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005127 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005128 return result;
5129 }
John Kessenich140f3df2015-06-26 16:58:36 -06005130
5131 switch (op) {
5132 case glslang::EOpLessThan:
5133 if (isFloat)
5134 binOp = spv::OpFOrdLessThan;
5135 else if (isUnsigned)
5136 binOp = spv::OpULessThan;
5137 else
5138 binOp = spv::OpSLessThan;
5139 break;
5140 case glslang::EOpGreaterThan:
5141 if (isFloat)
5142 binOp = spv::OpFOrdGreaterThan;
5143 else if (isUnsigned)
5144 binOp = spv::OpUGreaterThan;
5145 else
5146 binOp = spv::OpSGreaterThan;
5147 break;
5148 case glslang::EOpLessThanEqual:
5149 if (isFloat)
5150 binOp = spv::OpFOrdLessThanEqual;
5151 else if (isUnsigned)
5152 binOp = spv::OpULessThanEqual;
5153 else
5154 binOp = spv::OpSLessThanEqual;
5155 break;
5156 case glslang::EOpGreaterThanEqual:
5157 if (isFloat)
5158 binOp = spv::OpFOrdGreaterThanEqual;
5159 else if (isUnsigned)
5160 binOp = spv::OpUGreaterThanEqual;
5161 else
5162 binOp = spv::OpSGreaterThanEqual;
5163 break;
5164 case glslang::EOpEqual:
5165 case glslang::EOpVectorEqual:
5166 if (isFloat)
5167 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005168 else if (isBool)
5169 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 else
5171 binOp = spv::OpIEqual;
5172 break;
5173 case glslang::EOpNotEqual:
5174 case glslang::EOpVectorNotEqual:
5175 if (isFloat)
5176 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005177 else if (isBool)
5178 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005179 else
5180 binOp = spv::OpINotEqual;
5181 break;
5182 default:
5183 break;
5184 }
5185
qining25262b32016-05-06 17:25:16 -04005186 if (binOp != spv::OpNop) {
5187 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005188 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005189 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005190 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005191 }
John Kessenich140f3df2015-06-26 16:58:36 -06005192
5193 return 0;
5194}
5195
John Kessenich04bb8a02015-12-12 12:28:14 -07005196//
5197// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5198// These can be any of:
5199//
5200// matrix * scalar
5201// scalar * matrix
5202// matrix * matrix linear algebraic
5203// matrix * vector
5204// vector * matrix
5205// matrix * matrix componentwise
5206// matrix op matrix op in {+, -, /}
5207// matrix op scalar op in {+, -, /}
5208// scalar op matrix op in {+, -, /}
5209//
John Kessenichead86222018-03-28 18:01:20 -06005210spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5211 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005212{
5213 bool firstClass = true;
5214
5215 // First, handle first-class matrix operations (* and matrix/scalar)
5216 switch (op) {
5217 case spv::OpFDiv:
5218 if (builder.isMatrix(left) && builder.isScalar(right)) {
5219 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005220 spv::Id resultType = builder.getTypeId(right);
5221 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005222 op = spv::OpMatrixTimesScalar;
5223 } else
5224 firstClass = false;
5225 break;
5226 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005227 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005228 std::swap(left, right);
5229 assert(builder.isScalar(right));
5230 break;
5231 case spv::OpVectorTimesMatrix:
5232 assert(builder.isVector(left));
5233 assert(builder.isMatrix(right));
5234 break;
5235 case spv::OpMatrixTimesVector:
5236 assert(builder.isMatrix(left));
5237 assert(builder.isVector(right));
5238 break;
5239 case spv::OpMatrixTimesMatrix:
5240 assert(builder.isMatrix(left));
5241 assert(builder.isMatrix(right));
5242 break;
5243 default:
5244 firstClass = false;
5245 break;
5246 }
5247
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005248 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5249 firstClass = true;
5250
qining25262b32016-05-06 17:25:16 -04005251 if (firstClass) {
5252 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005253 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005254 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005255 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005256 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005257
LoopDawg592860c2016-06-09 08:57:35 -06005258 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005259 // The result type of all of them is the same type as the (a) matrix operand.
5260 // The algorithm is to:
5261 // - break the matrix(es) into vectors
5262 // - smear any scalar to a vector
5263 // - do vector operations
5264 // - make a matrix out the vector results
5265 switch (op) {
5266 case spv::OpFAdd:
5267 case spv::OpFSub:
5268 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005269 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005270 case spv::OpFMul:
5271 {
5272 // one time set up...
5273 bool leftMat = builder.isMatrix(left);
5274 bool rightMat = builder.isMatrix(right);
5275 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5276 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5277 spv::Id scalarType = builder.getScalarTypeId(typeId);
5278 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5279 std::vector<spv::Id> results;
5280 spv::Id smearVec = spv::NoResult;
5281 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005282 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005283 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005284 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005285
5286 // do each vector op
5287 for (unsigned int c = 0; c < numCols; ++c) {
5288 std::vector<unsigned int> indexes;
5289 indexes.push_back(c);
5290 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5291 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005292 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005293 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005294 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005295 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005296 }
5297
5298 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005299 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005300 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005301 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005302 }
5303 default:
5304 assert(0);
5305 return spv::NoResult;
5306 }
5307}
5308
John Kessenichead86222018-03-28 18:01:20 -06005309spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005310 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005311{
5312 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005313 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005315 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5316 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005317
5318 switch (op) {
5319 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005320 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005321 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005322 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005323 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005324 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005325 unaryOp = spv::OpSNegate;
5326 break;
5327
5328 case glslang::EOpLogicalNot:
5329 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005330 unaryOp = spv::OpLogicalNot;
5331 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 case glslang::EOpBitwiseNot:
5333 unaryOp = spv::OpNot;
5334 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005335
John Kessenich140f3df2015-06-26 16:58:36 -06005336 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005337 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005338 break;
5339 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005340 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005341 break;
5342 case glslang::EOpTranspose:
5343 unaryOp = spv::OpTranspose;
5344 break;
5345
5346 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005347 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005348 break;
5349 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005350 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005351 break;
5352 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005353 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005354 break;
5355 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005356 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005357 break;
5358 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005359 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005360 break;
5361 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005362 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005363 break;
5364 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005365 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005366 break;
5367 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005368 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005369 break;
5370
5371 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005372 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005373 break;
5374 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005375 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005376 break;
5377 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005378 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005379 break;
5380 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005381 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005382 break;
5383 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005384 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005385 break;
5386 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005387 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005388 break;
5389
5390 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005391 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005392 break;
5393 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005394 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005395 break;
5396
5397 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005398 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005399 break;
5400 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005401 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005402 break;
5403 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005404 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005405 break;
5406 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005407 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005408 break;
5409 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005410 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005411 break;
5412 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005413 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005414 break;
5415
5416 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005417 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005420 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005421 break;
5422 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005423 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005424 break;
5425 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005426 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005427 break;
5428 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005429 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005430 break;
5431 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005432 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005433 break;
5434
5435 case glslang::EOpIsNan:
5436 unaryOp = spv::OpIsNan;
5437 break;
5438 case glslang::EOpIsInf:
5439 unaryOp = spv::OpIsInf;
5440 break;
LoopDawg592860c2016-06-09 08:57:35 -06005441 case glslang::EOpIsFinite:
5442 unaryOp = spv::OpIsFinite;
5443 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005444
Rex Xucbc426e2015-12-15 16:03:10 +08005445 case glslang::EOpFloatBitsToInt:
5446 case glslang::EOpFloatBitsToUint:
5447 case glslang::EOpIntBitsToFloat:
5448 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005449 case glslang::EOpDoubleBitsToInt64:
5450 case glslang::EOpDoubleBitsToUint64:
5451 case glslang::EOpInt64BitsToDouble:
5452 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005453 case glslang::EOpFloat16BitsToInt16:
5454 case glslang::EOpFloat16BitsToUint16:
5455 case glslang::EOpInt16BitsToFloat16:
5456 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005457 unaryOp = spv::OpBitcast;
5458 break;
5459
John Kessenich140f3df2015-06-26 16:58:36 -06005460 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005473 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005478 case glslang::EOpPackSnorm4x8:
5479 libCall = spv::GLSLstd450PackSnorm4x8;
5480 break;
5481 case glslang::EOpUnpackSnorm4x8:
5482 libCall = spv::GLSLstd450UnpackSnorm4x8;
5483 break;
5484 case glslang::EOpPackUnorm4x8:
5485 libCall = spv::GLSLstd450PackUnorm4x8;
5486 break;
5487 case glslang::EOpUnpackUnorm4x8:
5488 libCall = spv::GLSLstd450UnpackUnorm4x8;
5489 break;
5490 case glslang::EOpPackDouble2x32:
5491 libCall = spv::GLSLstd450PackDouble2x32;
5492 break;
5493 case glslang::EOpUnpackDouble2x32:
5494 libCall = spv::GLSLstd450UnpackDouble2x32;
5495 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005496
Rex Xu8ff43de2016-04-22 16:51:45 +08005497 case glslang::EOpPackInt2x32:
5498 case glslang::EOpUnpackInt2x32:
5499 case glslang::EOpPackUint2x32:
5500 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005501 case glslang::EOpPack16:
5502 case glslang::EOpPack32:
5503 case glslang::EOpPack64:
5504 case glslang::EOpUnpack32:
5505 case glslang::EOpUnpack16:
5506 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005507 case glslang::EOpPackInt2x16:
5508 case glslang::EOpUnpackInt2x16:
5509 case glslang::EOpPackUint2x16:
5510 case glslang::EOpUnpackUint2x16:
5511 case glslang::EOpPackInt4x16:
5512 case glslang::EOpUnpackInt4x16:
5513 case glslang::EOpPackUint4x16:
5514 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005515 case glslang::EOpPackFloat2x16:
5516 case glslang::EOpUnpackFloat2x16:
5517 unaryOp = spv::OpBitcast;
5518 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005519
John Kessenich140f3df2015-06-26 16:58:36 -06005520 case glslang::EOpDPdx:
5521 unaryOp = spv::OpDPdx;
5522 break;
5523 case glslang::EOpDPdy:
5524 unaryOp = spv::OpDPdy;
5525 break;
5526 case glslang::EOpFwidth:
5527 unaryOp = spv::OpFwidth;
5528 break;
5529 case glslang::EOpDPdxFine:
5530 unaryOp = spv::OpDPdxFine;
5531 break;
5532 case glslang::EOpDPdyFine:
5533 unaryOp = spv::OpDPdyFine;
5534 break;
5535 case glslang::EOpFwidthFine:
5536 unaryOp = spv::OpFwidthFine;
5537 break;
5538 case glslang::EOpDPdxCoarse:
5539 unaryOp = spv::OpDPdxCoarse;
5540 break;
5541 case glslang::EOpDPdyCoarse:
5542 unaryOp = spv::OpDPdyCoarse;
5543 break;
5544 case glslang::EOpFwidthCoarse:
5545 unaryOp = spv::OpFwidthCoarse;
5546 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005547 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005548#ifdef AMD_EXTENSIONS
5549 if (typeProxy == glslang::EbtFloat16)
5550 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5551#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005552 libCall = spv::GLSLstd450InterpolateAtCentroid;
5553 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 case glslang::EOpAny:
5555 unaryOp = spv::OpAny;
5556 break;
5557 case glslang::EOpAll:
5558 unaryOp = spv::OpAll;
5559 break;
5560
5561 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005562 if (isFloat)
5563 libCall = spv::GLSLstd450FAbs;
5564 else
5565 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005566 break;
5567 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005568 if (isFloat)
5569 libCall = spv::GLSLstd450FSign;
5570 else
5571 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005572 break;
5573
John Kessenichfc51d282015-08-19 13:34:18 -06005574 case glslang::EOpAtomicCounterIncrement:
5575 case glslang::EOpAtomicCounterDecrement:
5576 case glslang::EOpAtomicCounter:
5577 {
5578 // Handle all of the atomics in one place, in createAtomicOperation()
5579 std::vector<spv::Id> operands;
5580 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005581 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005582 }
5583
John Kessenichfc51d282015-08-19 13:34:18 -06005584 case glslang::EOpBitFieldReverse:
5585 unaryOp = spv::OpBitReverse;
5586 break;
5587 case glslang::EOpBitCount:
5588 unaryOp = spv::OpBitCount;
5589 break;
5590 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005591 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005592 break;
5593 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005594 if (isUnsigned)
5595 libCall = spv::GLSLstd450FindUMsb;
5596 else
5597 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005598 break;
5599
Rex Xu574ab042016-04-14 16:53:07 +08005600 case glslang::EOpBallot:
5601 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005602 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005603 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005604 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005605#ifdef AMD_EXTENSIONS
5606 case glslang::EOpMinInvocations:
5607 case glslang::EOpMaxInvocations:
5608 case glslang::EOpAddInvocations:
5609 case glslang::EOpMinInvocationsNonUniform:
5610 case glslang::EOpMaxInvocationsNonUniform:
5611 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005612 case glslang::EOpMinInvocationsInclusiveScan:
5613 case glslang::EOpMaxInvocationsInclusiveScan:
5614 case glslang::EOpAddInvocationsInclusiveScan:
5615 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5616 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5617 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5618 case glslang::EOpMinInvocationsExclusiveScan:
5619 case glslang::EOpMaxInvocationsExclusiveScan:
5620 case glslang::EOpAddInvocationsExclusiveScan:
5621 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5622 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5623 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005624#endif
Rex Xu51596642016-09-21 18:56:12 +08005625 {
5626 std::vector<spv::Id> operands;
5627 operands.push_back(operand);
5628 return createInvocationsOperation(op, typeId, operands, typeProxy);
5629 }
John Kessenich66011cb2018-03-06 16:12:04 -07005630 case glslang::EOpSubgroupAll:
5631 case glslang::EOpSubgroupAny:
5632 case glslang::EOpSubgroupAllEqual:
5633 case glslang::EOpSubgroupBroadcastFirst:
5634 case glslang::EOpSubgroupBallot:
5635 case glslang::EOpSubgroupInverseBallot:
5636 case glslang::EOpSubgroupBallotBitCount:
5637 case glslang::EOpSubgroupBallotInclusiveBitCount:
5638 case glslang::EOpSubgroupBallotExclusiveBitCount:
5639 case glslang::EOpSubgroupBallotFindLSB:
5640 case glslang::EOpSubgroupBallotFindMSB:
5641 case glslang::EOpSubgroupAdd:
5642 case glslang::EOpSubgroupMul:
5643 case glslang::EOpSubgroupMin:
5644 case glslang::EOpSubgroupMax:
5645 case glslang::EOpSubgroupAnd:
5646 case glslang::EOpSubgroupOr:
5647 case glslang::EOpSubgroupXor:
5648 case glslang::EOpSubgroupInclusiveAdd:
5649 case glslang::EOpSubgroupInclusiveMul:
5650 case glslang::EOpSubgroupInclusiveMin:
5651 case glslang::EOpSubgroupInclusiveMax:
5652 case glslang::EOpSubgroupInclusiveAnd:
5653 case glslang::EOpSubgroupInclusiveOr:
5654 case glslang::EOpSubgroupInclusiveXor:
5655 case glslang::EOpSubgroupExclusiveAdd:
5656 case glslang::EOpSubgroupExclusiveMul:
5657 case glslang::EOpSubgroupExclusiveMin:
5658 case glslang::EOpSubgroupExclusiveMax:
5659 case glslang::EOpSubgroupExclusiveAnd:
5660 case glslang::EOpSubgroupExclusiveOr:
5661 case glslang::EOpSubgroupExclusiveXor:
5662 case glslang::EOpSubgroupQuadSwapHorizontal:
5663 case glslang::EOpSubgroupQuadSwapVertical:
5664 case glslang::EOpSubgroupQuadSwapDiagonal: {
5665 std::vector<spv::Id> operands;
5666 operands.push_back(operand);
5667 return createSubgroupOperation(op, typeId, operands, typeProxy);
5668 }
Rex Xu9d93a232016-05-05 12:30:44 +08005669#ifdef AMD_EXTENSIONS
5670 case glslang::EOpMbcnt:
5671 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5672 libCall = spv::MbcntAMD;
5673 break;
5674
5675 case glslang::EOpCubeFaceIndex:
5676 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5677 libCall = spv::CubeFaceIndexAMD;
5678 break;
5679
5680 case glslang::EOpCubeFaceCoord:
5681 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5682 libCall = spv::CubeFaceCoordAMD;
5683 break;
5684#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005685#ifdef NV_EXTENSIONS
5686 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005687 unaryOp = spv::OpGroupNonUniformPartitionNV;
5688 break;
5689#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005690 case glslang::EOpConstructReference:
5691 unaryOp = spv::OpBitcast;
5692 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005693
5694 case glslang::EOpCopyObject:
5695 unaryOp = spv::OpCopyObject;
5696 break;
5697
John Kessenich140f3df2015-06-26 16:58:36 -06005698 default:
5699 return 0;
5700 }
5701
5702 spv::Id id;
5703 if (libCall >= 0) {
5704 std::vector<spv::Id> args;
5705 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005706 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005707 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005708 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005709 }
John Kessenich140f3df2015-06-26 16:58:36 -06005710
John Kessenichead86222018-03-28 18:01:20 -06005711 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005712 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005713 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005714}
5715
John Kessenich7a53f762016-01-20 11:19:27 -07005716// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005717spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5718 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005719{
5720 // Handle unary operations vector by vector.
5721 // The result type is the same type as the original type.
5722 // The algorithm is to:
5723 // - break the matrix into vectors
5724 // - apply the operation to each vector
5725 // - make a matrix out the vector results
5726
5727 // get the types sorted out
5728 int numCols = builder.getNumColumns(operand);
5729 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005730 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5731 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005732 std::vector<spv::Id> results;
5733
5734 // do each vector op
5735 for (int c = 0; c < numCols; ++c) {
5736 std::vector<unsigned int> indexes;
5737 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005738 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5739 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005740 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005741 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005742 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005743 }
5744
5745 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005746 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005747 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005748 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005749}
5750
John Kessenichad7645f2018-06-04 19:11:25 -06005751// For converting integers where both the bitwidth and the signedness could
5752// change, but only do the width change here. The caller is still responsible
5753// for the signedness conversion.
5754spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005755{
John Kessenichad7645f2018-06-04 19:11:25 -06005756 // Get the result type width, based on the type to convert to.
5757 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005758 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005759 case glslang::EOpConvInt16ToUint8:
5760 case glslang::EOpConvIntToUint8:
5761 case glslang::EOpConvInt64ToUint8:
5762 case glslang::EOpConvUint16ToInt8:
5763 case glslang::EOpConvUintToInt8:
5764 case glslang::EOpConvUint64ToInt8:
5765 width = 8;
5766 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005767 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005768 case glslang::EOpConvIntToUint16:
5769 case glslang::EOpConvInt64ToUint16:
5770 case glslang::EOpConvUint8ToInt16:
5771 case glslang::EOpConvUintToInt16:
5772 case glslang::EOpConvUint64ToInt16:
5773 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005774 break;
5775 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005776 case glslang::EOpConvInt16ToUint:
5777 case glslang::EOpConvInt64ToUint:
5778 case glslang::EOpConvUint8ToInt:
5779 case glslang::EOpConvUint16ToInt:
5780 case glslang::EOpConvUint64ToInt:
5781 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005782 break;
5783 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005784 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005785 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005786 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005787 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005788 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005789 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005790 break;
5791
5792 default:
5793 assert(false && "Default missing");
5794 break;
5795 }
5796
John Kessenichad7645f2018-06-04 19:11:25 -06005797 // Get the conversion operation and result type,
5798 // based on the target width, but the source type.
5799 spv::Id type = spv::NoType;
5800 spv::Op convOp = spv::OpNop;
5801 switch(op) {
5802 case glslang::EOpConvInt8ToUint16:
5803 case glslang::EOpConvInt8ToUint:
5804 case glslang::EOpConvInt8ToUint64:
5805 case glslang::EOpConvInt16ToUint8:
5806 case glslang::EOpConvInt16ToUint:
5807 case glslang::EOpConvInt16ToUint64:
5808 case glslang::EOpConvIntToUint8:
5809 case glslang::EOpConvIntToUint16:
5810 case glslang::EOpConvIntToUint64:
5811 case glslang::EOpConvInt64ToUint8:
5812 case glslang::EOpConvInt64ToUint16:
5813 case glslang::EOpConvInt64ToUint:
5814 convOp = spv::OpSConvert;
5815 type = builder.makeIntType(width);
5816 break;
5817 default:
5818 convOp = spv::OpUConvert;
5819 type = builder.makeUintType(width);
5820 break;
5821 }
5822
John Kessenich66011cb2018-03-06 16:12:04 -07005823 if (vectorSize > 0)
5824 type = builder.makeVectorType(type, vectorSize);
5825
John Kessenichad7645f2018-06-04 19:11:25 -06005826 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005827}
5828
John Kessenichead86222018-03-28 18:01:20 -06005829spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5830 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005831{
5832 spv::Op convOp = spv::OpNop;
5833 spv::Id zero = 0;
5834 spv::Id one = 0;
5835
5836 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5837
5838 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005839 case glslang::EOpConvInt8ToBool:
5840 case glslang::EOpConvUint8ToBool:
5841 zero = builder.makeUint8Constant(0);
5842 zero = makeSmearedConstant(zero, vectorSize);
5843 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005844 case glslang::EOpConvInt16ToBool:
5845 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005846 zero = builder.makeUint16Constant(0);
5847 zero = makeSmearedConstant(zero, vectorSize);
5848 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5849 case glslang::EOpConvIntToBool:
5850 case glslang::EOpConvUintToBool:
5851 zero = builder.makeUintConstant(0);
5852 zero = makeSmearedConstant(zero, vectorSize);
5853 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5854 case glslang::EOpConvInt64ToBool:
5855 case glslang::EOpConvUint64ToBool:
5856 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005857 zero = makeSmearedConstant(zero, vectorSize);
5858 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5859
5860 case glslang::EOpConvFloatToBool:
5861 zero = builder.makeFloatConstant(0.0F);
5862 zero = makeSmearedConstant(zero, vectorSize);
5863 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5864
5865 case glslang::EOpConvDoubleToBool:
5866 zero = builder.makeDoubleConstant(0.0);
5867 zero = makeSmearedConstant(zero, vectorSize);
5868 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5869
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005870 case glslang::EOpConvFloat16ToBool:
5871 zero = builder.makeFloat16Constant(0.0F);
5872 zero = makeSmearedConstant(zero, vectorSize);
5873 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005874
John Kessenich140f3df2015-06-26 16:58:36 -06005875 case glslang::EOpConvBoolToFloat:
5876 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005877 zero = builder.makeFloatConstant(0.0F);
5878 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005880
John Kessenich140f3df2015-06-26 16:58:36 -06005881 case glslang::EOpConvBoolToDouble:
5882 convOp = spv::OpSelect;
5883 zero = builder.makeDoubleConstant(0.0);
5884 one = builder.makeDoubleConstant(1.0);
5885 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005886
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005887 case glslang::EOpConvBoolToFloat16:
5888 convOp = spv::OpSelect;
5889 zero = builder.makeFloat16Constant(0.0F);
5890 one = builder.makeFloat16Constant(1.0F);
5891 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005892
5893 case glslang::EOpConvBoolToInt8:
5894 zero = builder.makeInt8Constant(0);
5895 one = builder.makeInt8Constant(1);
5896 convOp = spv::OpSelect;
5897 break;
5898
5899 case glslang::EOpConvBoolToUint8:
5900 zero = builder.makeUint8Constant(0);
5901 one = builder.makeUint8Constant(1);
5902 convOp = spv::OpSelect;
5903 break;
5904
5905 case glslang::EOpConvBoolToInt16:
5906 zero = builder.makeInt16Constant(0);
5907 one = builder.makeInt16Constant(1);
5908 convOp = spv::OpSelect;
5909 break;
5910
5911 case glslang::EOpConvBoolToUint16:
5912 zero = builder.makeUint16Constant(0);
5913 one = builder.makeUint16Constant(1);
5914 convOp = spv::OpSelect;
5915 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005916
John Kessenich140f3df2015-06-26 16:58:36 -06005917 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005918 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005919 if (op == glslang::EOpConvBoolToInt64)
5920 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005921 else
5922 zero = builder.makeIntConstant(0);
5923
5924 if (op == glslang::EOpConvBoolToInt64)
5925 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005926 else
5927 one = builder.makeIntConstant(1);
5928
John Kessenich140f3df2015-06-26 16:58:36 -06005929 convOp = spv::OpSelect;
5930 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005931
John Kessenich140f3df2015-06-26 16:58:36 -06005932 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005933 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005934 if (op == glslang::EOpConvBoolToUint64)
5935 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005936 else
5937 zero = builder.makeUintConstant(0);
5938
5939 if (op == glslang::EOpConvBoolToUint64)
5940 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005941 else
5942 one = builder.makeUintConstant(1);
5943
John Kessenich140f3df2015-06-26 16:58:36 -06005944 convOp = spv::OpSelect;
5945 break;
5946
John Kessenich66011cb2018-03-06 16:12:04 -07005947 case glslang::EOpConvInt8ToFloat16:
5948 case glslang::EOpConvInt8ToFloat:
5949 case glslang::EOpConvInt8ToDouble:
5950 case glslang::EOpConvInt16ToFloat16:
5951 case glslang::EOpConvInt16ToFloat:
5952 case glslang::EOpConvInt16ToDouble:
5953 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005954 case glslang::EOpConvIntToFloat:
5955 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005956 case glslang::EOpConvInt64ToFloat:
5957 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005958 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005959 convOp = spv::OpConvertSToF;
5960 break;
5961
John Kessenich66011cb2018-03-06 16:12:04 -07005962 case glslang::EOpConvUint8ToFloat16:
5963 case glslang::EOpConvUint8ToFloat:
5964 case glslang::EOpConvUint8ToDouble:
5965 case glslang::EOpConvUint16ToFloat16:
5966 case glslang::EOpConvUint16ToFloat:
5967 case glslang::EOpConvUint16ToDouble:
5968 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005969 case glslang::EOpConvUintToFloat:
5970 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005971 case glslang::EOpConvUint64ToFloat:
5972 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005973 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005974 convOp = spv::OpConvertUToF;
5975 break;
5976
5977 case glslang::EOpConvDoubleToFloat:
5978 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005979 case glslang::EOpConvDoubleToFloat16:
5980 case glslang::EOpConvFloat16ToDouble:
5981 case glslang::EOpConvFloatToFloat16:
5982 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005983 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005984 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005985 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005986 break;
5987
John Kessenich66011cb2018-03-06 16:12:04 -07005988 case glslang::EOpConvFloat16ToInt8:
5989 case glslang::EOpConvFloatToInt8:
5990 case glslang::EOpConvDoubleToInt8:
5991 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005992 case glslang::EOpConvFloatToInt16:
5993 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005994 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005995 case glslang::EOpConvFloatToInt:
5996 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005997 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005998 case glslang::EOpConvFloatToInt64:
5999 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006000 convOp = spv::OpConvertFToS;
6001 break;
6002
John Kessenich66011cb2018-03-06 16:12:04 -07006003 case glslang::EOpConvUint8ToInt8:
6004 case glslang::EOpConvInt8ToUint8:
6005 case glslang::EOpConvUint16ToInt16:
6006 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006007 case glslang::EOpConvUintToInt:
6008 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006009 case glslang::EOpConvUint64ToInt64:
6010 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006011 if (builder.isInSpecConstCodeGenMode()) {
6012 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006013 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6014 zero = builder.makeUint8Constant(0);
6015 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006016 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006017 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6018 zero = builder.makeUint64Constant(0);
6019 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006020 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006021 }
qining189b2032016-04-12 23:16:20 -04006022 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006023 // Use OpIAdd, instead of OpBitcast to do the conversion when
6024 // generating for OpSpecConstantOp instruction.
6025 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6026 }
6027 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006028 convOp = spv::OpBitcast;
6029 break;
6030
John Kessenich66011cb2018-03-06 16:12:04 -07006031 case glslang::EOpConvFloat16ToUint8:
6032 case glslang::EOpConvFloatToUint8:
6033 case glslang::EOpConvDoubleToUint8:
6034 case glslang::EOpConvFloat16ToUint16:
6035 case glslang::EOpConvFloatToUint16:
6036 case glslang::EOpConvDoubleToUint16:
6037 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006038 case glslang::EOpConvFloatToUint:
6039 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006040 case glslang::EOpConvFloatToUint64:
6041 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006042 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006043 convOp = spv::OpConvertFToU;
6044 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006045
John Kessenich66011cb2018-03-06 16:12:04 -07006046 case glslang::EOpConvInt8ToInt16:
6047 case glslang::EOpConvInt8ToInt:
6048 case glslang::EOpConvInt8ToInt64:
6049 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006050 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006051 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006052 case glslang::EOpConvIntToInt8:
6053 case glslang::EOpConvIntToInt16:
6054 case glslang::EOpConvIntToInt64:
6055 case glslang::EOpConvInt64ToInt8:
6056 case glslang::EOpConvInt64ToInt16:
6057 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006058 convOp = spv::OpSConvert;
6059 break;
6060
John Kessenich66011cb2018-03-06 16:12:04 -07006061 case glslang::EOpConvUint8ToUint16:
6062 case glslang::EOpConvUint8ToUint:
6063 case glslang::EOpConvUint8ToUint64:
6064 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006065 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006066 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006067 case glslang::EOpConvUintToUint8:
6068 case glslang::EOpConvUintToUint16:
6069 case glslang::EOpConvUintToUint64:
6070 case glslang::EOpConvUint64ToUint8:
6071 case glslang::EOpConvUint64ToUint16:
6072 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006073 convOp = spv::OpUConvert;
6074 break;
6075
John Kessenich66011cb2018-03-06 16:12:04 -07006076 case glslang::EOpConvInt8ToUint16:
6077 case glslang::EOpConvInt8ToUint:
6078 case glslang::EOpConvInt8ToUint64:
6079 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006080 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006081 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006082 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006083 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006084 case glslang::EOpConvIntToUint64:
6085 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006086 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006087 case glslang::EOpConvInt64ToUint:
6088 case glslang::EOpConvUint8ToInt16:
6089 case glslang::EOpConvUint8ToInt:
6090 case glslang::EOpConvUint8ToInt64:
6091 case glslang::EOpConvUint16ToInt8:
6092 case glslang::EOpConvUint16ToInt:
6093 case glslang::EOpConvUint16ToInt64:
6094 case glslang::EOpConvUintToInt8:
6095 case glslang::EOpConvUintToInt16:
6096 case glslang::EOpConvUintToInt64:
6097 case glslang::EOpConvUint64ToInt8:
6098 case glslang::EOpConvUint64ToInt16:
6099 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006100 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006101 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006102
6103 if (builder.isInSpecConstCodeGenMode()) {
6104 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006105 switch(op) {
6106 case glslang::EOpConvInt16ToUint8:
6107 case glslang::EOpConvIntToUint8:
6108 case glslang::EOpConvInt64ToUint8:
6109 case glslang::EOpConvUint16ToInt8:
6110 case glslang::EOpConvUintToInt8:
6111 case glslang::EOpConvUint64ToInt8:
6112 zero = builder.makeUint8Constant(0);
6113 break;
6114 case glslang::EOpConvInt8ToUint16:
6115 case glslang::EOpConvIntToUint16:
6116 case glslang::EOpConvInt64ToUint16:
6117 case glslang::EOpConvUint8ToInt16:
6118 case glslang::EOpConvUintToInt16:
6119 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006120 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006121 break;
6122 case glslang::EOpConvInt8ToUint:
6123 case glslang::EOpConvInt16ToUint:
6124 case glslang::EOpConvInt64ToUint:
6125 case glslang::EOpConvUint8ToInt:
6126 case glslang::EOpConvUint16ToInt:
6127 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006128 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006129 break;
6130 case glslang::EOpConvInt8ToUint64:
6131 case glslang::EOpConvInt16ToUint64:
6132 case glslang::EOpConvIntToUint64:
6133 case glslang::EOpConvUint8ToInt64:
6134 case glslang::EOpConvUint16ToInt64:
6135 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006136 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006137 break;
6138 default:
6139 assert(false && "Default missing");
6140 break;
6141 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006142 zero = makeSmearedConstant(zero, vectorSize);
6143 // Use OpIAdd, instead of OpBitcast to do the conversion when
6144 // generating for OpSpecConstantOp instruction.
6145 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6146 }
6147 // For normal run-time conversion instruction, use OpBitcast.
6148 convOp = spv::OpBitcast;
6149 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006150 case glslang::EOpConvUint64ToPtr:
6151 convOp = spv::OpConvertUToPtr;
6152 break;
6153 case glslang::EOpConvPtrToUint64:
6154 convOp = spv::OpConvertPtrToU;
6155 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006156 default:
6157 break;
6158 }
6159
6160 spv::Id result = 0;
6161 if (convOp == spv::OpNop)
6162 return result;
6163
6164 if (convOp == spv::OpSelect) {
6165 zero = makeSmearedConstant(zero, vectorSize);
6166 one = makeSmearedConstant(one, vectorSize);
6167 result = builder.createTriOp(convOp, destType, operand, one, zero);
6168 } else
6169 result = builder.createUnaryOp(convOp, destType, operand);
6170
John Kessenichead86222018-03-28 18:01:20 -06006171 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006172 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006173 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006174}
6175
6176spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6177{
6178 if (vectorSize == 0)
6179 return constant;
6180
6181 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6182 std::vector<spv::Id> components;
6183 for (int c = 0; c < vectorSize; ++c)
6184 components.push_back(constant);
6185 return builder.makeCompositeConstant(vectorTypeId, components);
6186}
6187
John Kessenich426394d2015-07-23 10:22:48 -06006188// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006189spv::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 -06006190{
6191 spv::Op opCode = spv::OpNop;
6192
6193 switch (op) {
6194 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006195 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006196 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006197 opCode = spv::OpAtomicIAdd;
6198 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006199 case glslang::EOpAtomicCounterSubtract:
6200 opCode = spv::OpAtomicISub;
6201 break;
John Kessenich426394d2015-07-23 10:22:48 -06006202 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006203 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006204 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006205 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006206 break;
6207 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006208 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006209 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006210 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006211 break;
6212 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006213 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006214 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006215 opCode = spv::OpAtomicAnd;
6216 break;
6217 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006218 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006219 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006220 opCode = spv::OpAtomicOr;
6221 break;
6222 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006223 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006224 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006225 opCode = spv::OpAtomicXor;
6226 break;
6227 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006228 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006229 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006230 opCode = spv::OpAtomicExchange;
6231 break;
6232 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006233 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006234 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006235 opCode = spv::OpAtomicCompareExchange;
6236 break;
6237 case glslang::EOpAtomicCounterIncrement:
6238 opCode = spv::OpAtomicIIncrement;
6239 break;
6240 case glslang::EOpAtomicCounterDecrement:
6241 opCode = spv::OpAtomicIDecrement;
6242 break;
6243 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006244 case glslang::EOpImageAtomicLoad:
6245 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006246 opCode = spv::OpAtomicLoad;
6247 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006248 case glslang::EOpAtomicStore:
6249 case glslang::EOpImageAtomicStore:
6250 opCode = spv::OpAtomicStore;
6251 break;
John Kessenich426394d2015-07-23 10:22:48 -06006252 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006253 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006254 break;
6255 }
6256
Rex Xue8fe8b02017-09-26 15:42:56 +08006257 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6258 builder.addCapability(spv::CapabilityInt64Atomics);
6259
John Kessenich426394d2015-07-23 10:22:48 -06006260 // Sort out the operands
6261 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006262 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006263 // - compare-exchange swaps the value and comparator
6264 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006265 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006266 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6267 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6268 spv::Id scopeId;
6269 if (glslangIntermediate->usingVulkanMemoryModel()) {
6270 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6271 } else {
6272 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6273 }
6274 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006275 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006276 spv::Id semanticsId2 = semanticsId;
6277
6278 pointerId = operands[0];
6279 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6280 // no additional operands
6281 } else if (opCode == spv::OpAtomicCompareExchange) {
6282 compareId = operands[1];
6283 valueId = operands[2];
6284 if (operands.size() > 3) {
6285 scopeId = operands[3];
6286 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6287 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6288 }
6289 } else if (opCode == spv::OpAtomicLoad) {
6290 if (operands.size() > 1) {
6291 scopeId = operands[1];
6292 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6293 }
6294 } else {
6295 // atomic store or RMW
6296 valueId = operands[1];
6297 if (operands.size() > 2) {
6298 scopeId = operands[2];
6299 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6300 }
Rex Xu04db3f52015-09-16 11:44:02 +08006301 }
John Kessenich426394d2015-07-23 10:22:48 -06006302
Jeff Bolz36831c92018-09-05 10:11:41 -05006303 // Check for capabilities
6304 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006305 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6306 spv::MemorySemanticsMakeVisibleKHRMask |
6307 spv::MemorySemanticsOutputMemoryKHRMask |
6308 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006309 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6310 }
John Kessenich426394d2015-07-23 10:22:48 -06006311
Jeff Bolz36831c92018-09-05 10:11:41 -05006312 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6313 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6314 }
John Kessenich48d6e792017-10-06 21:21:48 -06006315
Jeff Bolz36831c92018-09-05 10:11:41 -05006316 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6317 spvAtomicOperands.push_back(pointerId);
6318 spvAtomicOperands.push_back(scopeId);
6319 spvAtomicOperands.push_back(semanticsId);
6320 if (opCode == spv::OpAtomicCompareExchange) {
6321 spvAtomicOperands.push_back(semanticsId2);
6322 spvAtomicOperands.push_back(valueId);
6323 spvAtomicOperands.push_back(compareId);
6324 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6325 spvAtomicOperands.push_back(valueId);
6326 }
John Kessenich48d6e792017-10-06 21:21:48 -06006327
Jeff Bolz36831c92018-09-05 10:11:41 -05006328 if (opCode == spv::OpAtomicStore) {
6329 builder.createNoResultOp(opCode, spvAtomicOperands);
6330 return 0;
6331 } else {
6332 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6333
6334 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6335 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6336 if (op == glslang::EOpAtomicCounterDecrement)
6337 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6338
6339 return resultId;
6340 }
John Kessenich426394d2015-07-23 10:22:48 -06006341}
6342
John Kessenich91cef522016-05-05 16:45:40 -06006343// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006344spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006345{
Corentin Walleze7061422018-08-08 15:20:15 +02006346#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006347 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6348 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006349#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006350
Rex Xu51596642016-09-21 18:56:12 +08006351 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006352 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006353 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6354
chaocf200da82016-12-20 12:44:35 -08006355 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6356 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006357 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6358 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006359 } else if (op == glslang::EOpAnyInvocation ||
6360 op == glslang::EOpAllInvocations ||
6361 op == glslang::EOpAllInvocationsEqual) {
6362 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6363 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006364 } else {
6365 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006366#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006367 if (op == glslang::EOpMinInvocationsNonUniform ||
6368 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006369 op == glslang::EOpAddInvocationsNonUniform ||
6370 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6371 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6372 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6373 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6374 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6375 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006376 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006377#endif
Rex Xu51596642016-09-21 18:56:12 +08006378
Rex Xu9d93a232016-05-05 12:30:44 +08006379#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006380 switch (op) {
6381 case glslang::EOpMinInvocations:
6382 case glslang::EOpMaxInvocations:
6383 case glslang::EOpAddInvocations:
6384 case glslang::EOpMinInvocationsNonUniform:
6385 case glslang::EOpMaxInvocationsNonUniform:
6386 case glslang::EOpAddInvocationsNonUniform:
6387 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006388 break;
6389 case glslang::EOpMinInvocationsInclusiveScan:
6390 case glslang::EOpMaxInvocationsInclusiveScan:
6391 case glslang::EOpAddInvocationsInclusiveScan:
6392 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6393 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6394 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6395 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006396 break;
6397 case glslang::EOpMinInvocationsExclusiveScan:
6398 case glslang::EOpMaxInvocationsExclusiveScan:
6399 case glslang::EOpAddInvocationsExclusiveScan:
6400 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6401 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6402 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6403 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006404 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006405 default:
6406 break;
Rex Xu430ef402016-10-14 17:22:23 +08006407 }
John Kessenich149afc32018-08-14 13:31:43 -06006408 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6409 spvGroupOperands.push_back(scope);
6410 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006411 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006412 spvGroupOperands.push_back(groupOp);
6413 }
Rex Xu9d93a232016-05-05 12:30:44 +08006414#endif
Rex Xu51596642016-09-21 18:56:12 +08006415 }
6416
John Kessenich149afc32018-08-14 13:31:43 -06006417 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6418 spv::IdImmediate op = { true, *opIt };
6419 spvGroupOperands.push_back(op);
6420 }
John Kessenich91cef522016-05-05 16:45:40 -06006421
6422 switch (op) {
6423 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006424 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006425 break;
John Kessenich91cef522016-05-05 16:45:40 -06006426 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006427 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006428 break;
John Kessenich91cef522016-05-05 16:45:40 -06006429 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006430 opCode = spv::OpSubgroupAllEqualKHR;
6431 break;
Rex Xu51596642016-09-21 18:56:12 +08006432 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006433 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006434 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006435 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006436 break;
6437 case glslang::EOpReadFirstInvocation:
6438 opCode = spv::OpSubgroupFirstInvocationKHR;
6439 break;
6440 case glslang::EOpBallot:
6441 {
6442 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6443 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6444 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6445 //
6446 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6447 //
6448 spv::Id uintType = builder.makeUintType(32);
6449 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6450 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6451
6452 std::vector<spv::Id> components;
6453 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6454 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6455
6456 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6457 return builder.createUnaryOp(spv::OpBitcast, typeId,
6458 builder.createCompositeConstruct(uvec2Type, components));
6459 }
6460
Rex Xu9d93a232016-05-05 12:30:44 +08006461#ifdef AMD_EXTENSIONS
6462 case glslang::EOpMinInvocations:
6463 case glslang::EOpMaxInvocations:
6464 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006465 case glslang::EOpMinInvocationsInclusiveScan:
6466 case glslang::EOpMaxInvocationsInclusiveScan:
6467 case glslang::EOpAddInvocationsInclusiveScan:
6468 case glslang::EOpMinInvocationsExclusiveScan:
6469 case glslang::EOpMaxInvocationsExclusiveScan:
6470 case glslang::EOpAddInvocationsExclusiveScan:
6471 if (op == glslang::EOpMinInvocations ||
6472 op == glslang::EOpMinInvocationsInclusiveScan ||
6473 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006474 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006475 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006476 else {
6477 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006478 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006479 else
Rex Xu51596642016-09-21 18:56:12 +08006480 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006481 }
Rex Xu430ef402016-10-14 17:22:23 +08006482 } else if (op == glslang::EOpMaxInvocations ||
6483 op == glslang::EOpMaxInvocationsInclusiveScan ||
6484 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006485 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006486 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006487 else {
6488 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006489 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006490 else
Rex Xu51596642016-09-21 18:56:12 +08006491 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006492 }
6493 } else {
6494 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006495 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006496 else
Rex Xu51596642016-09-21 18:56:12 +08006497 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006498 }
6499
Rex Xu2bbbe062016-08-23 15:41:05 +08006500 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006501 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006502
6503 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006504 case glslang::EOpMinInvocationsNonUniform:
6505 case glslang::EOpMaxInvocationsNonUniform:
6506 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006507 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6508 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6509 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6510 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6511 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6512 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6513 if (op == glslang::EOpMinInvocationsNonUniform ||
6514 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6515 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006516 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006517 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006518 else {
6519 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006520 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006521 else
Rex Xu51596642016-09-21 18:56:12 +08006522 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006523 }
6524 }
Rex Xu430ef402016-10-14 17:22:23 +08006525 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6526 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6527 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006528 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006529 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006530 else {
6531 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006532 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006533 else
Rex Xu51596642016-09-21 18:56:12 +08006534 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006535 }
6536 }
6537 else {
6538 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006539 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006540 else
Rex Xu51596642016-09-21 18:56:12 +08006541 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006542 }
6543
Rex Xu2bbbe062016-08-23 15:41:05 +08006544 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006545 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006546
6547 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006548#endif
John Kessenich91cef522016-05-05 16:45:40 -06006549 default:
6550 logger->missingFunctionality("invocation operation");
6551 return spv::NoResult;
6552 }
Rex Xu51596642016-09-21 18:56:12 +08006553
6554 assert(opCode != spv::OpNop);
6555 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006556}
6557
Rex Xu2bbbe062016-08-23 15:41:05 +08006558// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006559spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6560 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006561{
Rex Xub7072052016-09-26 15:53:40 +08006562#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006563 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6564 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006565 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006566 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006567 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6568 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6569 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006570#else
6571 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6572 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006573 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6574 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006575#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006576
6577 // Handle group invocation operations scalar by scalar.
6578 // The result type is the same type as the original type.
6579 // The algorithm is to:
6580 // - break the vector into scalars
6581 // - apply the operation to each scalar
6582 // - make a vector out the scalar results
6583
6584 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006585 int numComponents = builder.getNumComponents(operands[0]);
6586 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006587 std::vector<spv::Id> results;
6588
6589 // do each scalar op
6590 for (int comp = 0; comp < numComponents; ++comp) {
6591 std::vector<unsigned int> indexes;
6592 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006593 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6594 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006595 if (op == spv::OpSubgroupReadInvocationKHR) {
6596 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006597 spv::IdImmediate operand = { true, operands[1] };
6598 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006599 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006600 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6601 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006602 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006603 spv::IdImmediate operand = { true, operands[1] };
6604 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006605 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006606 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6607 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006608 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006609 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006610 spvGroupOperands.push_back(scalar);
6611 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006612
Rex Xub7072052016-09-26 15:53:40 +08006613 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006614 }
6615
6616 // put the pieces together
6617 return builder.createCompositeConstruct(typeId, results);
6618}
Rex Xu2bbbe062016-08-23 15:41:05 +08006619
John Kessenich66011cb2018-03-06 16:12:04 -07006620// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006621spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6622 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006623{
6624 // Add the required capabilities.
6625 switch (op) {
6626 case glslang::EOpSubgroupElect:
6627 builder.addCapability(spv::CapabilityGroupNonUniform);
6628 break;
6629 case glslang::EOpSubgroupAll:
6630 case glslang::EOpSubgroupAny:
6631 case glslang::EOpSubgroupAllEqual:
6632 builder.addCapability(spv::CapabilityGroupNonUniform);
6633 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6634 break;
6635 case glslang::EOpSubgroupBroadcast:
6636 case glslang::EOpSubgroupBroadcastFirst:
6637 case glslang::EOpSubgroupBallot:
6638 case glslang::EOpSubgroupInverseBallot:
6639 case glslang::EOpSubgroupBallotBitExtract:
6640 case glslang::EOpSubgroupBallotBitCount:
6641 case glslang::EOpSubgroupBallotInclusiveBitCount:
6642 case glslang::EOpSubgroupBallotExclusiveBitCount:
6643 case glslang::EOpSubgroupBallotFindLSB:
6644 case glslang::EOpSubgroupBallotFindMSB:
6645 builder.addCapability(spv::CapabilityGroupNonUniform);
6646 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6647 break;
6648 case glslang::EOpSubgroupShuffle:
6649 case glslang::EOpSubgroupShuffleXor:
6650 builder.addCapability(spv::CapabilityGroupNonUniform);
6651 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6652 break;
6653 case glslang::EOpSubgroupShuffleUp:
6654 case glslang::EOpSubgroupShuffleDown:
6655 builder.addCapability(spv::CapabilityGroupNonUniform);
6656 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6657 break;
6658 case glslang::EOpSubgroupAdd:
6659 case glslang::EOpSubgroupMul:
6660 case glslang::EOpSubgroupMin:
6661 case glslang::EOpSubgroupMax:
6662 case glslang::EOpSubgroupAnd:
6663 case glslang::EOpSubgroupOr:
6664 case glslang::EOpSubgroupXor:
6665 case glslang::EOpSubgroupInclusiveAdd:
6666 case glslang::EOpSubgroupInclusiveMul:
6667 case glslang::EOpSubgroupInclusiveMin:
6668 case glslang::EOpSubgroupInclusiveMax:
6669 case glslang::EOpSubgroupInclusiveAnd:
6670 case glslang::EOpSubgroupInclusiveOr:
6671 case glslang::EOpSubgroupInclusiveXor:
6672 case glslang::EOpSubgroupExclusiveAdd:
6673 case glslang::EOpSubgroupExclusiveMul:
6674 case glslang::EOpSubgroupExclusiveMin:
6675 case glslang::EOpSubgroupExclusiveMax:
6676 case glslang::EOpSubgroupExclusiveAnd:
6677 case glslang::EOpSubgroupExclusiveOr:
6678 case glslang::EOpSubgroupExclusiveXor:
6679 builder.addCapability(spv::CapabilityGroupNonUniform);
6680 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6681 break;
6682 case glslang::EOpSubgroupClusteredAdd:
6683 case glslang::EOpSubgroupClusteredMul:
6684 case glslang::EOpSubgroupClusteredMin:
6685 case glslang::EOpSubgroupClusteredMax:
6686 case glslang::EOpSubgroupClusteredAnd:
6687 case glslang::EOpSubgroupClusteredOr:
6688 case glslang::EOpSubgroupClusteredXor:
6689 builder.addCapability(spv::CapabilityGroupNonUniform);
6690 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6691 break;
6692 case glslang::EOpSubgroupQuadBroadcast:
6693 case glslang::EOpSubgroupQuadSwapHorizontal:
6694 case glslang::EOpSubgroupQuadSwapVertical:
6695 case glslang::EOpSubgroupQuadSwapDiagonal:
6696 builder.addCapability(spv::CapabilityGroupNonUniform);
6697 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6698 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006699#ifdef NV_EXTENSIONS
6700 case glslang::EOpSubgroupPartitionedAdd:
6701 case glslang::EOpSubgroupPartitionedMul:
6702 case glslang::EOpSubgroupPartitionedMin:
6703 case glslang::EOpSubgroupPartitionedMax:
6704 case glslang::EOpSubgroupPartitionedAnd:
6705 case glslang::EOpSubgroupPartitionedOr:
6706 case glslang::EOpSubgroupPartitionedXor:
6707 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6708 case glslang::EOpSubgroupPartitionedInclusiveMul:
6709 case glslang::EOpSubgroupPartitionedInclusiveMin:
6710 case glslang::EOpSubgroupPartitionedInclusiveMax:
6711 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6712 case glslang::EOpSubgroupPartitionedInclusiveOr:
6713 case glslang::EOpSubgroupPartitionedInclusiveXor:
6714 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6715 case glslang::EOpSubgroupPartitionedExclusiveMul:
6716 case glslang::EOpSubgroupPartitionedExclusiveMin:
6717 case glslang::EOpSubgroupPartitionedExclusiveMax:
6718 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6719 case glslang::EOpSubgroupPartitionedExclusiveOr:
6720 case glslang::EOpSubgroupPartitionedExclusiveXor:
6721 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6722 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6723 break;
6724#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006725 default: assert(0 && "Unhandled subgroup operation!");
6726 }
6727
6728 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6729 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6730 const bool isBool = typeProxy == glslang::EbtBool;
6731
6732 spv::Op opCode = spv::OpNop;
6733
6734 // Figure out which opcode to use.
6735 switch (op) {
6736 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6737 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6738 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6739 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6740 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6741 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6742 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6743 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6744 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6745 case glslang::EOpSubgroupBallotBitCount:
6746 case glslang::EOpSubgroupBallotInclusiveBitCount:
6747 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6748 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6749 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6750 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6751 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6752 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6753 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6754 case glslang::EOpSubgroupAdd:
6755 case glslang::EOpSubgroupInclusiveAdd:
6756 case glslang::EOpSubgroupExclusiveAdd:
6757 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006758#ifdef NV_EXTENSIONS
6759 case glslang::EOpSubgroupPartitionedAdd:
6760 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6761 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6762#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006763 if (isFloat) {
6764 opCode = spv::OpGroupNonUniformFAdd;
6765 } else {
6766 opCode = spv::OpGroupNonUniformIAdd;
6767 }
6768 break;
6769 case glslang::EOpSubgroupMul:
6770 case glslang::EOpSubgroupInclusiveMul:
6771 case glslang::EOpSubgroupExclusiveMul:
6772 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006773#ifdef NV_EXTENSIONS
6774 case glslang::EOpSubgroupPartitionedMul:
6775 case glslang::EOpSubgroupPartitionedInclusiveMul:
6776 case glslang::EOpSubgroupPartitionedExclusiveMul:
6777#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006778 if (isFloat) {
6779 opCode = spv::OpGroupNonUniformFMul;
6780 } else {
6781 opCode = spv::OpGroupNonUniformIMul;
6782 }
6783 break;
6784 case glslang::EOpSubgroupMin:
6785 case glslang::EOpSubgroupInclusiveMin:
6786 case glslang::EOpSubgroupExclusiveMin:
6787 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006788#ifdef NV_EXTENSIONS
6789 case glslang::EOpSubgroupPartitionedMin:
6790 case glslang::EOpSubgroupPartitionedInclusiveMin:
6791 case glslang::EOpSubgroupPartitionedExclusiveMin:
6792#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006793 if (isFloat) {
6794 opCode = spv::OpGroupNonUniformFMin;
6795 } else if (isUnsigned) {
6796 opCode = spv::OpGroupNonUniformUMin;
6797 } else {
6798 opCode = spv::OpGroupNonUniformSMin;
6799 }
6800 break;
6801 case glslang::EOpSubgroupMax:
6802 case glslang::EOpSubgroupInclusiveMax:
6803 case glslang::EOpSubgroupExclusiveMax:
6804 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006805#ifdef NV_EXTENSIONS
6806 case glslang::EOpSubgroupPartitionedMax:
6807 case glslang::EOpSubgroupPartitionedInclusiveMax:
6808 case glslang::EOpSubgroupPartitionedExclusiveMax:
6809#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006810 if (isFloat) {
6811 opCode = spv::OpGroupNonUniformFMax;
6812 } else if (isUnsigned) {
6813 opCode = spv::OpGroupNonUniformUMax;
6814 } else {
6815 opCode = spv::OpGroupNonUniformSMax;
6816 }
6817 break;
6818 case glslang::EOpSubgroupAnd:
6819 case glslang::EOpSubgroupInclusiveAnd:
6820 case glslang::EOpSubgroupExclusiveAnd:
6821 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006822#ifdef NV_EXTENSIONS
6823 case glslang::EOpSubgroupPartitionedAnd:
6824 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6825 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6826#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006827 if (isBool) {
6828 opCode = spv::OpGroupNonUniformLogicalAnd;
6829 } else {
6830 opCode = spv::OpGroupNonUniformBitwiseAnd;
6831 }
6832 break;
6833 case glslang::EOpSubgroupOr:
6834 case glslang::EOpSubgroupInclusiveOr:
6835 case glslang::EOpSubgroupExclusiveOr:
6836 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006837#ifdef NV_EXTENSIONS
6838 case glslang::EOpSubgroupPartitionedOr:
6839 case glslang::EOpSubgroupPartitionedInclusiveOr:
6840 case glslang::EOpSubgroupPartitionedExclusiveOr:
6841#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006842 if (isBool) {
6843 opCode = spv::OpGroupNonUniformLogicalOr;
6844 } else {
6845 opCode = spv::OpGroupNonUniformBitwiseOr;
6846 }
6847 break;
6848 case glslang::EOpSubgroupXor:
6849 case glslang::EOpSubgroupInclusiveXor:
6850 case glslang::EOpSubgroupExclusiveXor:
6851 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006852#ifdef NV_EXTENSIONS
6853 case glslang::EOpSubgroupPartitionedXor:
6854 case glslang::EOpSubgroupPartitionedInclusiveXor:
6855 case glslang::EOpSubgroupPartitionedExclusiveXor:
6856#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006857 if (isBool) {
6858 opCode = spv::OpGroupNonUniformLogicalXor;
6859 } else {
6860 opCode = spv::OpGroupNonUniformBitwiseXor;
6861 }
6862 break;
6863 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6864 case glslang::EOpSubgroupQuadSwapHorizontal:
6865 case glslang::EOpSubgroupQuadSwapVertical:
6866 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6867 default: assert(0 && "Unhandled subgroup operation!");
6868 }
6869
John Kessenich149afc32018-08-14 13:31:43 -06006870 // get the right Group Operation
6871 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006872 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006873 default:
6874 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006875 case glslang::EOpSubgroupBallotBitCount:
6876 case glslang::EOpSubgroupAdd:
6877 case glslang::EOpSubgroupMul:
6878 case glslang::EOpSubgroupMin:
6879 case glslang::EOpSubgroupMax:
6880 case glslang::EOpSubgroupAnd:
6881 case glslang::EOpSubgroupOr:
6882 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006883 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006884 break;
6885 case glslang::EOpSubgroupBallotInclusiveBitCount:
6886 case glslang::EOpSubgroupInclusiveAdd:
6887 case glslang::EOpSubgroupInclusiveMul:
6888 case glslang::EOpSubgroupInclusiveMin:
6889 case glslang::EOpSubgroupInclusiveMax:
6890 case glslang::EOpSubgroupInclusiveAnd:
6891 case glslang::EOpSubgroupInclusiveOr:
6892 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006893 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006894 break;
6895 case glslang::EOpSubgroupBallotExclusiveBitCount:
6896 case glslang::EOpSubgroupExclusiveAdd:
6897 case glslang::EOpSubgroupExclusiveMul:
6898 case glslang::EOpSubgroupExclusiveMin:
6899 case glslang::EOpSubgroupExclusiveMax:
6900 case glslang::EOpSubgroupExclusiveAnd:
6901 case glslang::EOpSubgroupExclusiveOr:
6902 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006903 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006904 break;
6905 case glslang::EOpSubgroupClusteredAdd:
6906 case glslang::EOpSubgroupClusteredMul:
6907 case glslang::EOpSubgroupClusteredMin:
6908 case glslang::EOpSubgroupClusteredMax:
6909 case glslang::EOpSubgroupClusteredAnd:
6910 case glslang::EOpSubgroupClusteredOr:
6911 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006912 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006913 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006914#ifdef NV_EXTENSIONS
6915 case glslang::EOpSubgroupPartitionedAdd:
6916 case glslang::EOpSubgroupPartitionedMul:
6917 case glslang::EOpSubgroupPartitionedMin:
6918 case glslang::EOpSubgroupPartitionedMax:
6919 case glslang::EOpSubgroupPartitionedAnd:
6920 case glslang::EOpSubgroupPartitionedOr:
6921 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006922 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006923 break;
6924 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6925 case glslang::EOpSubgroupPartitionedInclusiveMul:
6926 case glslang::EOpSubgroupPartitionedInclusiveMin:
6927 case glslang::EOpSubgroupPartitionedInclusiveMax:
6928 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6929 case glslang::EOpSubgroupPartitionedInclusiveOr:
6930 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006931 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006932 break;
6933 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6934 case glslang::EOpSubgroupPartitionedExclusiveMul:
6935 case glslang::EOpSubgroupPartitionedExclusiveMin:
6936 case glslang::EOpSubgroupPartitionedExclusiveMax:
6937 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6938 case glslang::EOpSubgroupPartitionedExclusiveOr:
6939 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006940 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006941 break;
6942#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006943 }
6944
John Kessenich149afc32018-08-14 13:31:43 -06006945 // build the instruction
6946 std::vector<spv::IdImmediate> spvGroupOperands;
6947
6948 // Every operation begins with the Execution Scope operand.
6949 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6950 spvGroupOperands.push_back(executionScope);
6951
6952 // Next, for all operations that use a Group Operation, push that as an operand.
6953 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006954 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006955 spvGroupOperands.push_back(groupOperand);
6956 }
6957
John Kessenich66011cb2018-03-06 16:12:04 -07006958 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006959 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6960 spv::IdImmediate operand = { true, *opIt };
6961 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006962 }
6963
6964 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006965 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006966 switch (op) {
6967 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006968 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6969 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6970 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6971 }
6972 if (directionId != spv::NoResult) {
6973 spv::IdImmediate direction = { true, directionId };
6974 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006975 }
6976
6977 return builder.createOp(opCode, typeId, spvGroupOperands);
6978}
6979
John Kessenich5e4b1242015-08-06 22:53:06 -06006980spv::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 -06006981{
John Kessenich66011cb2018-03-06 16:12:04 -07006982 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6983 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006984
John Kessenich140f3df2015-06-26 16:58:36 -06006985 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006987 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006988 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006989 spv::Id typeId0 = 0;
6990 if (consumedOperands > 0)
6991 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006992 spv::Id typeId1 = 0;
6993 if (consumedOperands > 1)
6994 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006995 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006996
6997 switch (op) {
6998 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006999 if (isFloat)
7000 libCall = spv::GLSLstd450FMin;
7001 else if (isUnsigned)
7002 libCall = spv::GLSLstd450UMin;
7003 else
7004 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007005 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007006 break;
7007 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007008 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007009 break;
7010 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007011 if (isFloat)
7012 libCall = spv::GLSLstd450FMax;
7013 else if (isUnsigned)
7014 libCall = spv::GLSLstd450UMax;
7015 else
7016 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007017 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007018 break;
7019 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007020 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007021 break;
7022 case glslang::EOpDot:
7023 opCode = spv::OpDot;
7024 break;
7025 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007026 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007027 break;
7028
7029 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007030 if (isFloat)
7031 libCall = spv::GLSLstd450FClamp;
7032 else if (isUnsigned)
7033 libCall = spv::GLSLstd450UClamp;
7034 else
7035 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007036 builder.promoteScalar(precision, operands.front(), operands[1]);
7037 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007038 break;
7039 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007040 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7041 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007042 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007043 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007044 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007045 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007046 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007047 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007048 break;
7049 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007050 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007051 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007052 break;
7053 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007054 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007055 builder.promoteScalar(precision, operands[0], operands[2]);
7056 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007057 break;
7058
7059 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007060 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007061 break;
7062 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007063 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007064 break;
7065 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007066 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007067 break;
7068 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007069 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007070 break;
7071 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007072 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007073 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007074 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007075#ifdef AMD_EXTENSIONS
7076 if (typeProxy == glslang::EbtFloat16)
7077 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7078#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007079 libCall = spv::GLSLstd450InterpolateAtSample;
7080 break;
7081 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007082#ifdef AMD_EXTENSIONS
7083 if (typeProxy == glslang::EbtFloat16)
7084 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7085#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007086 libCall = spv::GLSLstd450InterpolateAtOffset;
7087 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007088 case glslang::EOpAddCarry:
7089 opCode = spv::OpIAddCarry;
7090 typeId = builder.makeStructResultType(typeId0, typeId0);
7091 consumedOperands = 2;
7092 break;
7093 case glslang::EOpSubBorrow:
7094 opCode = spv::OpISubBorrow;
7095 typeId = builder.makeStructResultType(typeId0, typeId0);
7096 consumedOperands = 2;
7097 break;
7098 case glslang::EOpUMulExtended:
7099 opCode = spv::OpUMulExtended;
7100 typeId = builder.makeStructResultType(typeId0, typeId0);
7101 consumedOperands = 2;
7102 break;
7103 case glslang::EOpIMulExtended:
7104 opCode = spv::OpSMulExtended;
7105 typeId = builder.makeStructResultType(typeId0, typeId0);
7106 consumedOperands = 2;
7107 break;
7108 case glslang::EOpBitfieldExtract:
7109 if (isUnsigned)
7110 opCode = spv::OpBitFieldUExtract;
7111 else
7112 opCode = spv::OpBitFieldSExtract;
7113 break;
7114 case glslang::EOpBitfieldInsert:
7115 opCode = spv::OpBitFieldInsert;
7116 break;
7117
7118 case glslang::EOpFma:
7119 libCall = spv::GLSLstd450Fma;
7120 break;
7121 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007122 {
7123 libCall = spv::GLSLstd450FrexpStruct;
7124 assert(builder.isPointerType(typeId1));
7125 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007126 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007127#ifdef AMD_EXTENSIONS
7128 if (width == 16)
7129 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7130 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7131#endif
Rex Xu470026f2017-03-29 17:12:40 +08007132 if (builder.getNumComponents(operands[0]) == 1)
7133 frexpIntType = builder.makeIntegerType(width, true);
7134 else
7135 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7136 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7137 consumedOperands = 1;
7138 }
John Kessenich55e7d112015-11-15 21:33:39 -07007139 break;
7140 case glslang::EOpLdexp:
7141 libCall = spv::GLSLstd450Ldexp;
7142 break;
7143
Rex Xu574ab042016-04-14 16:53:07 +08007144 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007145 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007146
John Kessenich66011cb2018-03-06 16:12:04 -07007147 case glslang::EOpSubgroupBroadcast:
7148 case glslang::EOpSubgroupBallotBitExtract:
7149 case glslang::EOpSubgroupShuffle:
7150 case glslang::EOpSubgroupShuffleXor:
7151 case glslang::EOpSubgroupShuffleUp:
7152 case glslang::EOpSubgroupShuffleDown:
7153 case glslang::EOpSubgroupClusteredAdd:
7154 case glslang::EOpSubgroupClusteredMul:
7155 case glslang::EOpSubgroupClusteredMin:
7156 case glslang::EOpSubgroupClusteredMax:
7157 case glslang::EOpSubgroupClusteredAnd:
7158 case glslang::EOpSubgroupClusteredOr:
7159 case glslang::EOpSubgroupClusteredXor:
7160 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007161#ifdef NV_EXTENSIONS
7162 case glslang::EOpSubgroupPartitionedAdd:
7163 case glslang::EOpSubgroupPartitionedMul:
7164 case glslang::EOpSubgroupPartitionedMin:
7165 case glslang::EOpSubgroupPartitionedMax:
7166 case glslang::EOpSubgroupPartitionedAnd:
7167 case glslang::EOpSubgroupPartitionedOr:
7168 case glslang::EOpSubgroupPartitionedXor:
7169 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7170 case glslang::EOpSubgroupPartitionedInclusiveMul:
7171 case glslang::EOpSubgroupPartitionedInclusiveMin:
7172 case glslang::EOpSubgroupPartitionedInclusiveMax:
7173 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7174 case glslang::EOpSubgroupPartitionedInclusiveOr:
7175 case glslang::EOpSubgroupPartitionedInclusiveXor:
7176 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7177 case glslang::EOpSubgroupPartitionedExclusiveMul:
7178 case glslang::EOpSubgroupPartitionedExclusiveMin:
7179 case glslang::EOpSubgroupPartitionedExclusiveMax:
7180 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7181 case glslang::EOpSubgroupPartitionedExclusiveOr:
7182 case glslang::EOpSubgroupPartitionedExclusiveXor:
7183#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007184 return createSubgroupOperation(op, typeId, operands, typeProxy);
7185
Rex Xu9d93a232016-05-05 12:30:44 +08007186#ifdef AMD_EXTENSIONS
7187 case glslang::EOpSwizzleInvocations:
7188 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7189 libCall = spv::SwizzleInvocationsAMD;
7190 break;
7191 case glslang::EOpSwizzleInvocationsMasked:
7192 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7193 libCall = spv::SwizzleInvocationsMaskedAMD;
7194 break;
7195 case glslang::EOpWriteInvocation:
7196 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7197 libCall = spv::WriteInvocationAMD;
7198 break;
7199
7200 case glslang::EOpMin3:
7201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7202 if (isFloat)
7203 libCall = spv::FMin3AMD;
7204 else {
7205 if (isUnsigned)
7206 libCall = spv::UMin3AMD;
7207 else
7208 libCall = spv::SMin3AMD;
7209 }
7210 break;
7211 case glslang::EOpMax3:
7212 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7213 if (isFloat)
7214 libCall = spv::FMax3AMD;
7215 else {
7216 if (isUnsigned)
7217 libCall = spv::UMax3AMD;
7218 else
7219 libCall = spv::SMax3AMD;
7220 }
7221 break;
7222 case glslang::EOpMid3:
7223 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7224 if (isFloat)
7225 libCall = spv::FMid3AMD;
7226 else {
7227 if (isUnsigned)
7228 libCall = spv::UMid3AMD;
7229 else
7230 libCall = spv::SMid3AMD;
7231 }
7232 break;
7233
7234 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007235 if (typeProxy == glslang::EbtFloat16)
7236 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007237 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7238 libCall = spv::InterpolateAtVertexAMD;
7239 break;
7240#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007241 case glslang::EOpBarrier:
7242 {
7243 // This is for the extended controlBarrier function, with four operands.
7244 // The unextended barrier() goes through createNoArgOperation.
7245 assert(operands.size() == 4);
7246 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7247 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7248 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7249 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007250 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7251 spv::MemorySemanticsMakeVisibleKHRMask |
7252 spv::MemorySemanticsOutputMemoryKHRMask |
7253 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007254 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7255 }
7256 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7257 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7258 }
7259 return 0;
7260 }
7261 break;
7262 case glslang::EOpMemoryBarrier:
7263 {
7264 // This is for the extended memoryBarrier function, with three operands.
7265 // The unextended memoryBarrier() goes through createNoArgOperation.
7266 assert(operands.size() == 3);
7267 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7268 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7269 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007270 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7271 spv::MemorySemanticsMakeVisibleKHRMask |
7272 spv::MemorySemanticsOutputMemoryKHRMask |
7273 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007274 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7275 }
7276 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7277 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7278 }
7279 return 0;
7280 }
7281 break;
Chao Chen3c366992018-09-19 11:41:59 -07007282
7283#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007284 case glslang::EOpReportIntersectionNV:
7285 {
7286 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007287 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007288 }
7289 break;
7290 case glslang::EOpTraceNV:
7291 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007292 builder.createNoResultOp(spv::OpTraceNV, operands);
7293 return 0;
7294 }
7295 break;
7296 case glslang::EOpExecuteCallableNV:
7297 {
7298 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007299 return 0;
7300 }
7301 break;
Chao Chen3c366992018-09-19 11:41:59 -07007302 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7303 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7304 return 0;
7305#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007306 case glslang::EOpCooperativeMatrixMulAdd:
7307 opCode = spv::OpCooperativeMatrixMulAddNV;
7308 break;
7309
John Kessenich140f3df2015-06-26 16:58:36 -06007310 default:
7311 return 0;
7312 }
7313
7314 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007315 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007316 // Use an extended instruction from the standard library.
7317 // Construct the call arguments, without modifying the original operands vector.
7318 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7319 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007320 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007321 } else if (opCode == spv::OpDot && !isFloat) {
7322 // int dot(int, int)
7323 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7324 const int componentCount = builder.getNumComponents(operands[0]);
7325 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7326 builder.setPrecision(mulOp, precision);
7327 id = builder.createCompositeExtract(mulOp, typeId, 0);
7328 for (int i = 1; i < componentCount; ++i) {
7329 builder.setPrecision(id, precision);
7330 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7331 }
John Kessenich2359bd02015-12-06 19:29:11 -07007332 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007333 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007334 case 0:
7335 // should all be handled by visitAggregate and createNoArgOperation
7336 assert(0);
7337 return 0;
7338 case 1:
7339 // should all be handled by createUnaryOperation
7340 assert(0);
7341 return 0;
7342 case 2:
7343 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7344 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007345 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007346 // anything 3 or over doesn't have l-value operands, so all should be consumed
7347 assert(consumedOperands == operands.size());
7348 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007349 break;
7350 }
7351 }
7352
John Kessenich55e7d112015-11-15 21:33:39 -07007353 // Decode the return types that were structures
7354 switch (op) {
7355 case glslang::EOpAddCarry:
7356 case glslang::EOpSubBorrow:
7357 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7358 id = builder.createCompositeExtract(id, typeId0, 0);
7359 break;
7360 case glslang::EOpUMulExtended:
7361 case glslang::EOpIMulExtended:
7362 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7363 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7364 break;
7365 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007366 {
7367 assert(operands.size() == 2);
7368 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7369 // "exp" is floating-point type (from HLSL intrinsic)
7370 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7371 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7372 builder.createStore(member1, operands[1]);
7373 } else
7374 // "exp" is integer type (from GLSL built-in function)
7375 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7376 id = builder.createCompositeExtract(id, typeId0, 0);
7377 }
John Kessenich55e7d112015-11-15 21:33:39 -07007378 break;
7379 default:
7380 break;
7381 }
7382
John Kessenich32cfd492016-02-02 12:37:46 -07007383 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007384}
7385
Rex Xu9d93a232016-05-05 12:30:44 +08007386// Intrinsics with no arguments (or no return value, and no precision).
7387spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007388{
Jeff Bolz36831c92018-09-05 10:11:41 -05007389 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7390 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007391
7392 switch (op) {
7393 case glslang::EOpEmitVertex:
7394 builder.createNoResultOp(spv::OpEmitVertex);
7395 return 0;
7396 case glslang::EOpEndPrimitive:
7397 builder.createNoResultOp(spv::OpEndPrimitive);
7398 return 0;
7399 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007400 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007401 if (glslangIntermediate->usingVulkanMemoryModel()) {
7402 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7403 spv::MemorySemanticsOutputMemoryKHRMask |
7404 spv::MemorySemanticsAcquireReleaseMask);
7405 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7406 } else {
7407 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7408 }
John Kessenich82979362017-12-11 04:02:24 -07007409 } else {
7410 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7411 spv::MemorySemanticsWorkgroupMemoryMask |
7412 spv::MemorySemanticsAcquireReleaseMask);
7413 }
John Kessenich140f3df2015-06-26 16:58:36 -06007414 return 0;
7415 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007416 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7417 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007418 return 0;
7419 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007420 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7421 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007422 return 0;
7423 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007424 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7425 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007426 return 0;
7427 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007428 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7429 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007430 return 0;
7431 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007432 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7433 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007434 return 0;
7435 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007436 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7437 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007438 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007439 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007440 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007441 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007442 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007443 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007444 case glslang::EOpDeviceMemoryBarrier:
7445 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7446 spv::MemorySemanticsImageMemoryMask |
7447 spv::MemorySemanticsAcquireReleaseMask);
7448 return 0;
7449 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7450 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7451 spv::MemorySemanticsImageMemoryMask |
7452 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007453 return 0;
7454 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007455 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7456 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007457 return 0;
7458 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007459 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7460 spv::MemorySemanticsWorkgroupMemoryMask |
7461 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007462 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007463 case glslang::EOpSubgroupBarrier:
7464 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7465 spv::MemorySemanticsAcquireReleaseMask);
7466 return spv::NoResult;
7467 case glslang::EOpSubgroupMemoryBarrier:
7468 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7469 spv::MemorySemanticsAcquireReleaseMask);
7470 return spv::NoResult;
7471 case glslang::EOpSubgroupMemoryBarrierBuffer:
7472 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7473 spv::MemorySemanticsAcquireReleaseMask);
7474 return spv::NoResult;
7475 case glslang::EOpSubgroupMemoryBarrierImage:
7476 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7477 spv::MemorySemanticsAcquireReleaseMask);
7478 return spv::NoResult;
7479 case glslang::EOpSubgroupMemoryBarrierShared:
7480 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7481 spv::MemorySemanticsAcquireReleaseMask);
7482 return spv::NoResult;
7483 case glslang::EOpSubgroupElect: {
7484 std::vector<spv::Id> operands;
7485 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7486 }
Rex Xu9d93a232016-05-05 12:30:44 +08007487#ifdef AMD_EXTENSIONS
7488 case glslang::EOpTime:
7489 {
7490 std::vector<spv::Id> args; // Dummy arguments
7491 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7492 return builder.setPrecision(id, precision);
7493 }
7494#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007495#ifdef NV_EXTENSIONS
7496 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007497 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007498 return 0;
7499 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007500 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007501 return 0;
7502#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007503
7504 case glslang::EOpBeginInvocationInterlock:
7505 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7506 return 0;
7507 case glslang::EOpEndInvocationInterlock:
7508 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7509 return 0;
7510
John Kessenich140f3df2015-06-26 16:58:36 -06007511 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007512 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007513 return 0;
7514 }
7515}
7516
7517spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7518{
John Kessenich2f273362015-07-18 22:34:27 -06007519 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007520 spv::Id id;
7521 if (symbolValues.end() != iter) {
7522 id = iter->second;
7523 return id;
7524 }
7525
7526 // it was not found, create it
7527 id = createSpvVariable(symbol);
7528 symbolValues[symbol->getId()] = id;
7529
Rex Xuc884b4a2016-06-29 15:03:44 +08007530 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007531 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7532 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7533 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007534#ifdef NV_EXTENSIONS
7535 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7536#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007537 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007538 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007539 if (symbol->getQualifier().hasIndex())
7540 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7541 if (symbol->getQualifier().hasComponent())
7542 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007543 // atomic counters use this:
7544 if (symbol->getQualifier().hasOffset())
7545 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007546 }
7547
scygan2c864272016-05-18 18:09:17 +02007548 if (symbol->getQualifier().hasLocation())
7549 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007550 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007551 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007552 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007553 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007554 }
John Kessenich140f3df2015-06-26 16:58:36 -06007555 if (symbol->getQualifier().hasSet())
7556 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007557 else if (IsDescriptorResource(symbol->getType())) {
7558 // default to 0
7559 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7560 }
John Kessenich140f3df2015-06-26 16:58:36 -06007561 if (symbol->getQualifier().hasBinding())
7562 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007563 else if (IsDescriptorResource(symbol->getType())) {
7564 // default to 0
7565 builder.addDecoration(id, spv::DecorationBinding, 0);
7566 }
John Kessenich6c292d32016-02-15 20:58:50 -07007567 if (symbol->getQualifier().hasAttachment())
7568 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007569 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007570 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007571 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007572 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007573 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7574 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7575 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7576 }
7577 if (symbol->getQualifier().hasXfbOffset())
7578 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007579 }
7580
Rex Xu1da878f2016-02-21 20:59:01 +08007581 if (symbol->getType().isImage()) {
7582 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007583 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007584 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007585 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007586 }
7587
John Kessenich140f3df2015-06-26 16:58:36 -06007588 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007589 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007590 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007591 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007592
John Kessenich5611c6d2018-04-05 11:25:02 -06007593 // nonuniform
7594 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7595
John Kessenichecba76f2017-01-06 00:34:48 -07007596#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007597 if (builtIn == spv::BuiltInSampleMask) {
7598 spv::Decoration decoration;
7599 // GL_NV_sample_mask_override_coverage extension
7600 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007601 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007602 else
7603 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007604 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007605 if (decoration != spv::DecorationMax) {
7606 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7607 }
7608 }
chaoc771d89f2017-01-13 01:10:53 -08007609 else if (builtIn == spv::BuiltInLayer) {
7610 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007611 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007612 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007613 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7614 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7615 }
John Kessenichb41bff62017-08-11 13:07:17 -06007616 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007617 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7618 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007619 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7620 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7621 }
7622 }
7623
chaoc6e5acae2016-12-20 13:28:52 -08007624 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007625 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007626 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007627 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7628 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007629 if (symbol->getQualifier().pervertexNV) {
7630 builder.addDecoration(id, spv::DecorationPerVertexNV);
7631 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7632 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7633 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007634#endif
7635
John Kessenich5d610ee2018-03-07 18:05:55 -07007636 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7637 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7638 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7639 symbol->getType().getQualifier().semanticName);
7640 }
7641
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007642 if (symbol->getBasicType() == glslang::EbtReference) {
7643 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7644 }
7645
John Kessenich140f3df2015-06-26 16:58:36 -06007646 return id;
7647}
7648
Chao Chen3c366992018-09-19 11:41:59 -07007649#ifdef NV_EXTENSIONS
7650// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7651void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7652{
7653 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007654 if (qualifier.perPrimitiveNV) {
7655 // Need to add capability/extension for fragment shader.
7656 // Mesh shader already adds this by default.
7657 if (glslangIntermediate->getStage() == EShLangFragment) {
7658 builder.addCapability(spv::CapabilityMeshShadingNV);
7659 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7660 }
Chao Chen3c366992018-09-19 11:41:59 -07007661 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007662 }
Chao Chen3c366992018-09-19 11:41:59 -07007663 if (qualifier.perViewNV)
7664 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7665 if (qualifier.perTaskNV)
7666 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7667 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007668 if (qualifier.perPrimitiveNV) {
7669 // Need to add capability/extension for fragment shader.
7670 // Mesh shader already adds this by default.
7671 if (glslangIntermediate->getStage() == EShLangFragment) {
7672 builder.addCapability(spv::CapabilityMeshShadingNV);
7673 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7674 }
Chao Chen3c366992018-09-19 11:41:59 -07007675 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007676 }
Chao Chen3c366992018-09-19 11:41:59 -07007677 if (qualifier.perViewNV)
7678 builder.addDecoration(id, spv::DecorationPerViewNV);
7679 if (qualifier.perTaskNV)
7680 builder.addDecoration(id, spv::DecorationPerTaskNV);
7681 }
7682}
7683#endif
7684
John Kessenich55e7d112015-11-15 21:33:39 -07007685// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007686// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007687//
7688// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7689//
7690// Recursively walk the nodes. The nodes form a tree whose leaves are
7691// regular constants, which themselves are trees that createSpvConstant()
7692// recursively walks. So, this function walks the "top" of the tree:
7693// - emit specialization constant-building instructions for specConstant
7694// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007695spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007696{
John Kessenich7cc0e282016-03-20 00:46:02 -06007697 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007698
qining4f4bb812016-04-03 23:55:17 -04007699 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007700 if (! node.getQualifier().specConstant) {
7701 // hand off to the non-spec-constant path
7702 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7703 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007704 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007705 nextConst, false);
7706 }
7707
7708 // We now know we have a specialization constant to build
7709
John Kessenichd94c0032016-05-30 19:29:40 -06007710 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007711 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7712 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7713 std::vector<spv::Id> dimConstId;
7714 for (int dim = 0; dim < 3; ++dim) {
7715 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7716 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007717 if (specConst) {
7718 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7719 glslangIntermediate->getLocalSizeSpecId(dim));
7720 }
qining4f4bb812016-04-03 23:55:17 -04007721 }
7722 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7723 }
7724
7725 // An AST node labelled as specialization constant should be a symbol node.
7726 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7727 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007728 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007729 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007730 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7731 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7732 // will set the builder into spec constant op instruction generating mode.
7733 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007734 result = accessChainLoad(sub_tree->getType());
7735 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007736 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007737 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007738 } else {
7739 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007740 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007741 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007742 builder.addName(result, sn->getName().c_str());
7743 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007744 }
qining4f4bb812016-04-03 23:55:17 -04007745
7746 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7747 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007748 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007749 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007750}
7751
John Kessenich140f3df2015-06-26 16:58:36 -06007752// Use 'consts' as the flattened glslang source of scalar constants to recursively
7753// build the aggregate SPIR-V constant.
7754//
7755// If there are not enough elements present in 'consts', 0 will be substituted;
7756// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7757//
qining08408382016-03-21 09:51:37 -04007758spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007759{
7760 // vector of constants for SPIR-V
7761 std::vector<spv::Id> spvConsts;
7762
7763 // Type is used for struct and array constants
7764 spv::Id typeId = convertGlslangToSpvType(glslangType);
7765
7766 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007767 glslang::TType elementType(glslangType, 0);
7768 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007769 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007770 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007771 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007772 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007773 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007774 } else if (glslangType.isCoopMat()) {
7775 glslang::TType componentType(glslangType.getBasicType());
7776 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007777 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007778 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7779 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007780 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007781 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007782 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7783 bool zero = nextConst >= consts.size();
7784 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007785 case glslang::EbtInt8:
7786 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7787 break;
7788 case glslang::EbtUint8:
7789 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7790 break;
7791 case glslang::EbtInt16:
7792 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7793 break;
7794 case glslang::EbtUint16:
7795 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7796 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007797 case glslang::EbtInt:
7798 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7799 break;
7800 case glslang::EbtUint:
7801 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7802 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007803 case glslang::EbtInt64:
7804 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7805 break;
7806 case glslang::EbtUint64:
7807 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7808 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007809 case glslang::EbtFloat:
7810 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7811 break;
7812 case glslang::EbtDouble:
7813 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7814 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007815 case glslang::EbtFloat16:
7816 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7817 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007818 case glslang::EbtBool:
7819 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7820 break;
7821 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007822 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007823 break;
7824 }
7825 ++nextConst;
7826 }
7827 } else {
7828 // we have a non-aggregate (scalar) constant
7829 bool zero = nextConst >= consts.size();
7830 spv::Id scalar = 0;
7831 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007832 case glslang::EbtInt8:
7833 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7834 break;
7835 case glslang::EbtUint8:
7836 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7837 break;
7838 case glslang::EbtInt16:
7839 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7840 break;
7841 case glslang::EbtUint16:
7842 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7843 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007844 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007845 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007846 break;
7847 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007848 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007849 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007850 case glslang::EbtInt64:
7851 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7852 break;
7853 case glslang::EbtUint64:
7854 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7855 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007856 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007857 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007858 break;
7859 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007860 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007861 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007862 case glslang::EbtFloat16:
7863 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7864 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007865 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007866 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007867 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007868 case glslang::EbtReference:
7869 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7870 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7871 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007872 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007873 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007874 break;
7875 }
7876 ++nextConst;
7877 return scalar;
7878 }
7879
7880 return builder.makeCompositeConstant(typeId, spvConsts);
7881}
7882
John Kessenich7c1aa102015-10-15 13:29:11 -06007883// Return true if the node is a constant or symbol whose reading has no
7884// non-trivial observable cost or effect.
7885bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7886{
7887 // don't know what this is
7888 if (node == nullptr)
7889 return false;
7890
7891 // a constant is safe
7892 if (node->getAsConstantUnion() != nullptr)
7893 return true;
7894
7895 // not a symbol means non-trivial
7896 if (node->getAsSymbolNode() == nullptr)
7897 return false;
7898
7899 // a symbol, depends on what's being read
7900 switch (node->getType().getQualifier().storage) {
7901 case glslang::EvqTemporary:
7902 case glslang::EvqGlobal:
7903 case glslang::EvqIn:
7904 case glslang::EvqInOut:
7905 case glslang::EvqConst:
7906 case glslang::EvqConstReadOnly:
7907 case glslang::EvqUniform:
7908 return true;
7909 default:
7910 return false;
7911 }
qining25262b32016-05-06 17:25:16 -04007912}
John Kessenich7c1aa102015-10-15 13:29:11 -06007913
7914// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007915// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007916// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007917// Return true if trivial.
7918bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7919{
7920 if (node == nullptr)
7921 return false;
7922
John Kessenich84cc15f2017-05-24 16:44:47 -06007923 // count non scalars as trivial, as well as anything coming from HLSL
7924 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007925 return true;
7926
John Kessenich7c1aa102015-10-15 13:29:11 -06007927 // symbols and constants are trivial
7928 if (isTrivialLeaf(node))
7929 return true;
7930
7931 // otherwise, it needs to be a simple operation or one or two leaf nodes
7932
7933 // not a simple operation
7934 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7935 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7936 if (binaryNode == nullptr && unaryNode == nullptr)
7937 return false;
7938
7939 // not on leaf nodes
7940 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7941 return false;
7942
7943 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7944 return false;
7945 }
7946
7947 switch (node->getAsOperator()->getOp()) {
7948 case glslang::EOpLogicalNot:
7949 case glslang::EOpConvIntToBool:
7950 case glslang::EOpConvUintToBool:
7951 case glslang::EOpConvFloatToBool:
7952 case glslang::EOpConvDoubleToBool:
7953 case glslang::EOpEqual:
7954 case glslang::EOpNotEqual:
7955 case glslang::EOpLessThan:
7956 case glslang::EOpGreaterThan:
7957 case glslang::EOpLessThanEqual:
7958 case glslang::EOpGreaterThanEqual:
7959 case glslang::EOpIndexDirect:
7960 case glslang::EOpIndexDirectStruct:
7961 case glslang::EOpLogicalXor:
7962 case glslang::EOpAny:
7963 case glslang::EOpAll:
7964 return true;
7965 default:
7966 return false;
7967 }
7968}
7969
7970// Emit short-circuiting code, where 'right' is never evaluated unless
7971// the left side is true (for &&) or false (for ||).
7972spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7973{
7974 spv::Id boolTypeId = builder.makeBoolType();
7975
7976 // emit left operand
7977 builder.clearAccessChain();
7978 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007979 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007980
7981 // Operands to accumulate OpPhi operands
7982 std::vector<spv::Id> phiOperands;
7983 // accumulate left operand's phi information
7984 phiOperands.push_back(leftId);
7985 phiOperands.push_back(builder.getBuildPoint()->getId());
7986
7987 // Make the two kinds of operation symmetric with a "!"
7988 // || => emit "if (! left) result = right"
7989 // && => emit "if ( left) result = right"
7990 //
7991 // TODO: this runtime "not" for || could be avoided by adding functionality
7992 // to 'builder' to have an "else" without an "then"
7993 if (op == glslang::EOpLogicalOr)
7994 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7995
7996 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007997 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007998
7999 // emit right operand as the "then" part of the "if"
8000 builder.clearAccessChain();
8001 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008002 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008003
8004 // accumulate left operand's phi information
8005 phiOperands.push_back(rightId);
8006 phiOperands.push_back(builder.getBuildPoint()->getId());
8007
8008 // finish the "if"
8009 ifBuilder.makeEndIf();
8010
8011 // phi together the two results
8012 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8013}
8014
Frank Henigman541f7bb2018-01-16 00:18:26 -05008015#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008016// Return type Id of the imported set of extended instructions corresponds to the name.
8017// Import this set if it has not been imported yet.
8018spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8019{
8020 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8021 return extBuiltinMap[name];
8022 else {
Rex Xu51596642016-09-21 18:56:12 +08008023 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008024 spv::Id extBuiltins = builder.import(name);
8025 extBuiltinMap[name] = extBuiltins;
8026 return extBuiltins;
8027 }
8028}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008029#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008030
John Kessenich140f3df2015-06-26 16:58:36 -06008031}; // end anonymous namespace
8032
8033namespace glslang {
8034
John Kessenich68d78fd2015-07-12 19:28:10 -06008035void GetSpirvVersion(std::string& version)
8036{
John Kessenich9e55f632015-07-15 10:03:39 -06008037 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008038 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008039 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008040 version = buf;
8041}
8042
John Kessenicha372a3e2017-11-02 22:32:14 -06008043// For low-order part of the generator's magic number. Bump up
8044// when there is a change in the style (e.g., if SSA form changes,
8045// or a different instruction sequence to do something gets used).
8046int GetSpirvGeneratorVersion()
8047{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008048 // return 1; // start
8049 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008050 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008051 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008052 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008053 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8054 // versions 4 and 6 each generate OpArrayLength as it has long been done
8055 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008056}
8057
John Kessenich140f3df2015-06-26 16:58:36 -06008058// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008059void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008060{
8061 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008062 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008063 if (out.fail())
8064 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008065 for (int i = 0; i < (int)spirv.size(); ++i) {
8066 unsigned int word = spirv[i];
8067 out.write((const char*)&word, 4);
8068 }
8069 out.close();
8070}
8071
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008072// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008073void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008074{
8075 std::ofstream out;
8076 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008077 if (out.fail())
8078 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008079 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008080 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008081 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008082 if (varName != nullptr) {
8083 out << "\t #pragma once" << std::endl;
8084 out << "const uint32_t " << varName << "[] = {" << std::endl;
8085 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008086 const int WORDS_PER_LINE = 8;
8087 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8088 out << "\t";
8089 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8090 const unsigned int word = spirv[i + j];
8091 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8092 if (i + j + 1 < (int)spirv.size()) {
8093 out << ",";
8094 }
8095 }
8096 out << std::endl;
8097 }
Flavio15017db2017-02-15 14:29:33 -08008098 if (varName != nullptr) {
8099 out << "};";
8100 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008101 out.close();
8102}
8103
John Kessenich140f3df2015-06-26 16:58:36 -06008104//
8105// Set up the glslang traversal
8106//
John Kessenich4e11b612018-08-30 16:56:59 -06008107void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008108{
Lei Zhang17535f72016-05-04 15:55:59 -04008109 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008110 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008111}
8112
John Kessenich4e11b612018-08-30 16:56:59 -06008113void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008114 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008115{
John Kessenich140f3df2015-06-26 16:58:36 -06008116 TIntermNode* root = intermediate.getTreeRoot();
8117
8118 if (root == 0)
8119 return;
8120
John Kessenich4e11b612018-08-30 16:56:59 -06008121 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008122 if (options == nullptr)
8123 options = &defaultOptions;
8124
John Kessenich4e11b612018-08-30 16:56:59 -06008125 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008126
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008127 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008128 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008129 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008130 it.dumpSpv(spirv);
8131
GregFfb03a552018-03-29 11:49:14 -06008132#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008133 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8134 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008135 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8136 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008137 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008138 prelegalization = false;
8139 }
John Kessenich717c80a2018-08-23 15:17:10 -06008140
John Kessenich4e11b612018-08-30 16:56:59 -06008141 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008142 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008143
John Kessenich717c80a2018-08-23 15:17:10 -06008144 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008145 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008146
GregFcd1f1692017-09-21 18:40:22 -06008147#endif
8148
John Kessenich4e11b612018-08-30 16:56:59 -06008149 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008150}
8151
8152}; // end namespace glslang