blob: fbfb335cf1c86c05036f76e1a1d94467380d7c6c [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 Kessenicha2858d92018-01-31 08:11:18 -0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
891 // raytracing
892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700928 case glslang::EbvTaskCountNV:
929 return spv::BuiltInTaskCountNV;
930 case glslang::EbvPrimitiveCountNV:
931 return spv::BuiltInPrimitiveCountNV;
932 case glslang::EbvPrimitiveIndicesNV:
933 return spv::BuiltInPrimitiveIndicesNV;
934 case glslang::EbvClipDistancePerViewNV:
935 return spv::BuiltInClipDistancePerViewNV;
936 case glslang::EbvCullDistancePerViewNV:
937 return spv::BuiltInCullDistancePerViewNV;
938 case glslang::EbvLayerPerViewNV:
939 return spv::BuiltInLayerPerViewNV;
940 case glslang::EbvMeshViewCountNV:
941 return spv::BuiltInMeshViewCountNV;
942 case glslang::EbvMeshViewIndicesNV:
943 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800944#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800945 default:
946 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948}
949
Rex Xufc618912015-09-09 16:42:49 +0800950// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700951spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800952{
953 assert(type.getBasicType() == glslang::EbtSampler);
954
John Kessenich5d0fa972016-02-15 11:57:00 -0700955 // Check for capabilities
956 switch (type.getQualifier().layoutFormat) {
957 case glslang::ElfRg32f:
958 case glslang::ElfRg16f:
959 case glslang::ElfR11fG11fB10f:
960 case glslang::ElfR16f:
961 case glslang::ElfRgba16:
962 case glslang::ElfRgb10A2:
963 case glslang::ElfRg16:
964 case glslang::ElfRg8:
965 case glslang::ElfR16:
966 case glslang::ElfR8:
967 case glslang::ElfRgba16Snorm:
968 case glslang::ElfRg16Snorm:
969 case glslang::ElfRg8Snorm:
970 case glslang::ElfR16Snorm:
971 case glslang::ElfR8Snorm:
972
973 case glslang::ElfRg32i:
974 case glslang::ElfRg16i:
975 case glslang::ElfRg8i:
976 case glslang::ElfR16i:
977 case glslang::ElfR8i:
978
979 case glslang::ElfRgb10a2ui:
980 case glslang::ElfRg32ui:
981 case glslang::ElfRg16ui:
982 case glslang::ElfRg8ui:
983 case glslang::ElfR16ui:
984 case glslang::ElfR8ui:
985 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
986 break;
987
988 default:
989 break;
990 }
991
992 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800993 switch (type.getQualifier().layoutFormat) {
994 case glslang::ElfNone: return spv::ImageFormatUnknown;
995 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
996 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
997 case glslang::ElfR32f: return spv::ImageFormatR32f;
998 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
999 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1000 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1001 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1002 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1003 case glslang::ElfR16f: return spv::ImageFormatR16f;
1004 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1005 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1006 case glslang::ElfRg16: return spv::ImageFormatRg16;
1007 case glslang::ElfRg8: return spv::ImageFormatRg8;
1008 case glslang::ElfR16: return spv::ImageFormatR16;
1009 case glslang::ElfR8: return spv::ImageFormatR8;
1010 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1011 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1012 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1013 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1014 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1015 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1016 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1017 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1018 case glslang::ElfR32i: return spv::ImageFormatR32i;
1019 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1020 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1021 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1022 case glslang::ElfR16i: return spv::ImageFormatR16i;
1023 case glslang::ElfR8i: return spv::ImageFormatR8i;
1024 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1025 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1026 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1027 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1028 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1029 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1030 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1031 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1032 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1033 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001035 }
1036}
1037
John Kesseniche18fd202018-01-30 11:01:39 -07001038spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001039{
John Kesseniche18fd202018-01-30 11:01:39 -07001040 if (selectionNode.getFlatten())
1041 return spv::SelectionControlFlattenMask;
1042 if (selectionNode.getDontFlatten())
1043 return spv::SelectionControlDontFlattenMask;
1044 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (switchNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (switchNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
1054}
1055
John Kessenicha2858d92018-01-31 08:11:18 -07001056// return a non-0 dependency if the dependency argument must be set
1057spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1058 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001059{
1060 spv::LoopControlMask control = spv::LoopControlMaskNone;
1061
1062 if (loopNode.getDontUnroll())
1063 control = control | spv::LoopControlDontUnrollMask;
1064 if (loopNode.getUnroll())
1065 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001066 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001067 control = control | spv::LoopControlDependencyInfiniteMask;
1068 else if (loopNode.getLoopDependency() > 0) {
1069 control = control | spv::LoopControlDependencyLengthMask;
1070 dependencyLength = loopNode.getLoopDependency();
1071 }
John Kesseniche18fd202018-01-30 11:01:39 -07001072
1073 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001074}
1075
John Kessenicha5c5fb62017-05-05 05:09:58 -06001076// Translate glslang type to SPIR-V storage class.
1077spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1078{
1079 if (type.getQualifier().isPipeInput())
1080 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001081 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001082 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001083
1084 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1085 type.getQualifier().storage == glslang::EvqUniform) {
1086 if (type.getBasicType() == glslang::EbtAtomicUint)
1087 return spv::StorageClassAtomicCounter;
1088 if (type.containsOpaque())
1089 return spv::StorageClassUniformConstant;
1090 }
1091
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001092#ifdef NV_EXTENSIONS
1093 if (type.getQualifier().isUniformOrBuffer() &&
1094 type.getQualifier().layoutShaderRecordNV) {
1095 return spv::StorageClassShaderRecordBufferNV;
1096 }
1097#endif
1098
John Kessenichbed4e4f2017-09-08 02:38:07 -06001099 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001100 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001101 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001102 }
1103
1104 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001105 if (type.getQualifier().layoutPushConstant)
1106 return spv::StorageClassPushConstant;
1107 if (type.getBasicType() == glslang::EbtBlock)
1108 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001110 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001111
1112 switch (type.getQualifier().storage) {
1113 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1114 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1115 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1116 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001117#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001118 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1119 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1120 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1121 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1122 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001123#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 default:
1125 assert(0);
1126 break;
1127 }
1128
1129 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001130}
1131
John Kessenich5611c6d2018-04-05 11:25:02 -06001132// Add capabilities pertaining to how an array is indexed.
1133void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1134 const glslang::TType& indexType)
1135{
1136 if (indexType.getQualifier().isNonUniform()) {
1137 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001138 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001139 if (baseType.getBasicType() == glslang::EbtSampler) {
1140 if (baseType.getQualifier().hasAttachment())
1141 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1142 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1143 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1144 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1145 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1146 else if (baseType.isImage())
1147 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1148 else if (baseType.isTexture())
1149 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1150 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1151 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1152 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1153 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1154 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1155 }
1156 } else {
1157 // assume a dynamically uniform index
1158 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001159 if (baseType.getQualifier().hasAttachment()) {
1160 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001162 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1163 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001164 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001165 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1166 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001168 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001169 }
1170 }
1171}
1172
qining25262b32016-05-06 17:25:16 -04001173// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001174// descriptor set.
1175bool IsDescriptorResource(const glslang::TType& type)
1176{
John Kessenichf7497e22016-03-08 21:36:22 -07001177 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001178 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001179 return type.getQualifier().isUniformOrBuffer() &&
1180#ifdef NV_EXTENSIONS
1181 ! type.getQualifier().layoutShaderRecordNV &&
1182#endif
1183 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001184
1185 // non block...
1186 // basically samplerXXX/subpass/sampler/texture are all included
1187 // if they are the global-scope-class, not the function parameter
1188 // (or local, if they ever exist) class.
1189 if (type.getBasicType() == glslang::EbtSampler)
1190 return type.getQualifier().isUniformOrBuffer();
1191
1192 // None of the above.
1193 return false;
1194}
1195
John Kesseniche0b6cad2015-12-24 10:30:13 -07001196void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1197{
1198 if (child.layoutMatrix == glslang::ElmNone)
1199 child.layoutMatrix = parent.layoutMatrix;
1200
1201 if (parent.invariant)
1202 child.invariant = true;
1203 if (parent.nopersp)
1204 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001205#ifdef AMD_EXTENSIONS
1206 if (parent.explicitInterp)
1207 child.explicitInterp = true;
1208#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001209 if (parent.flat)
1210 child.flat = true;
1211 if (parent.centroid)
1212 child.centroid = true;
1213 if (parent.patch)
1214 child.patch = true;
1215 if (parent.sample)
1216 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001217 if (parent.coherent)
1218 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001219 if (parent.devicecoherent)
1220 child.devicecoherent = true;
1221 if (parent.queuefamilycoherent)
1222 child.queuefamilycoherent = true;
1223 if (parent.workgroupcoherent)
1224 child.workgroupcoherent = true;
1225 if (parent.subgroupcoherent)
1226 child.subgroupcoherent = true;
1227 if (parent.nonprivate)
1228 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001229 if (parent.volatil)
1230 child.volatil = true;
1231 if (parent.restrict)
1232 child.restrict = true;
1233 if (parent.readonly)
1234 child.readonly = true;
1235 if (parent.writeonly)
1236 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001237#ifdef NV_EXTENSIONS
1238 if (parent.perPrimitiveNV)
1239 child.perPrimitiveNV = true;
1240 if (parent.perViewNV)
1241 child.perViewNV = true;
1242 if (parent.perTaskNV)
1243 child.perTaskNV = true;
1244#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001245}
1246
John Kessenichf2b7f332016-09-01 17:05:23 -06001247bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001248{
John Kessenich7b9fa252016-01-21 18:56:57 -07001249 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001250 // - struct members might inherit from a struct declaration
1251 // (note that non-block structs don't explicitly inherit,
1252 // only implicitly, meaning no decoration involved)
1253 // - affect decorations on the struct members
1254 // (note smooth does not, and expecting something like volatile
1255 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001256 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001257 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001258}
1259
John Kessenich140f3df2015-06-26 16:58:36 -06001260//
1261// Implement the TGlslangToSpvTraverser class.
1262//
1263
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001264TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001265 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1266 : TIntermTraverser(true, false, true),
1267 options(options),
1268 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001269 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001270 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001271 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001272 glslangIntermediate(glslangIntermediate)
1273{
1274 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1275
1276 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001277 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1278 glslangIntermediate->getVersion());
1279
John Kessenich121853f2017-05-31 17:11:16 -06001280 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001281 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001282 builder.setSourceFile(glslangIntermediate->getSourceFile());
1283
1284 // Set the source shader's text. If for SPV version 1.0, include
1285 // a preamble in comments stating the OpModuleProcessed instructions.
1286 // Otherwise, emit those as actual instructions.
1287 std::string text;
1288 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1289 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001290 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001291 text.append("// OpModuleProcessed ");
1292 text.append(processes[p]);
1293 text.append("\n");
1294 } else
1295 builder.addModuleProcessed(processes[p]);
1296 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001297 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001298 text.append("#line 1\n");
1299 text.append(glslangIntermediate->getSourceText());
1300 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001301 // Pass name and text for all included files
1302 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1303 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1304 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001305 }
John Kessenich140f3df2015-06-26 16:58:36 -06001306 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001307
1308 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1309 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1310
1311 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1312 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1313 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1314 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1315 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001316 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001317 memoryModel = spv::MemoryModelVulkanKHR;
1318 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001319 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001320 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001321 builder.setMemoryModel(addressingModel, memoryModel);
1322
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001323 if (glslangIntermediate->usingVariablePointers()) {
1324 builder.addCapability(spv::CapabilityVariablePointers);
1325 }
1326
John Kessenicheee9d532016-09-19 18:09:30 -06001327 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1328 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001331 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1332 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001333 builder.addSourceExtension(it->c_str());
1334
1335 // Add the top-level modes for this shader.
1336
John Kessenich92187592016-02-01 13:45:25 -07001337 if (glslangIntermediate->getXfbMode()) {
1338 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001339 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001340 }
John Kessenich140f3df2015-06-26 16:58:36 -06001341
1342 unsigned int mode;
1343 switch (glslangIntermediate->getStage()) {
1344 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001345 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001346 break;
1347
steve-lunarge7412492017-03-23 11:56:07 -06001348 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001349 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001350 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
steve-lunarge7412492017-03-23 11:56:07 -06001352 glslang::TLayoutGeometry primitive;
1353
1354 if (glslangIntermediate->getStage() == EShLangTessControl) {
1355 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1356 primitive = glslangIntermediate->getOutputPrimitive();
1357 } else {
1358 primitive = glslangIntermediate->getInputPrimitive();
1359 }
1360
1361 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001362 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1363 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1364 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001365 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001366 }
John Kessenich4016e382016-07-15 11:53:56 -06001367 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1369
John Kesseniche6903322015-10-13 16:29:02 -06001370 switch (glslangIntermediate->getVertexSpacing()) {
1371 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1372 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1373 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001374 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001375 }
John Kessenich4016e382016-07-15 11:53:56 -06001376 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001377 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1378
1379 switch (glslangIntermediate->getVertexOrder()) {
1380 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1381 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001382 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001383 }
John Kessenich4016e382016-07-15 11:53:56 -06001384 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001385 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1386
1387 if (glslangIntermediate->getPointMode())
1388 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001389 break;
1390
1391 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001392 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 switch (glslangIntermediate->getInputPrimitive()) {
1394 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1395 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1396 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001397 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001398 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001399 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001400 }
John Kessenich4016e382016-07-15 11:53:56 -06001401 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001402 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001403
John Kessenich140f3df2015-06-26 16:58:36 -06001404 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1405
1406 switch (glslangIntermediate->getOutputPrimitive()) {
1407 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1408 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1409 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001410 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001411 }
John Kessenich4016e382016-07-15 11:53:56 -06001412 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001413 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1414 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1415 break;
1416
1417 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001418 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 if (glslangIntermediate->getPixelCenterInteger())
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 if (glslangIntermediate->getOriginUpperLeft())
1423 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001424 else
1425 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001426
1427 if (glslangIntermediate->getEarlyFragmentTests())
1428 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1429
chaocc1204522017-06-30 17:14:30 -07001430 if (glslangIntermediate->getPostDepthCoverage()) {
1431 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1433 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1434 }
1435
John Kesseniche6903322015-10-13 16:29:02 -06001436 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001437 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1438 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001439 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001440 }
John Kessenich4016e382016-07-15 11:53:56 -06001441 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001442 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1443
1444 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 break;
1447
1448 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001449 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1451 glslangIntermediate->getLocalSize(1),
1452 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001453#ifdef NV_EXTENSIONS
1454 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1455 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1457 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1458 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1459 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1461 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1462 }
1463#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001464 break;
1465
Chao Chen3c366992018-09-19 11:41:59 -07001466#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001467 case EShLangRayGenNV:
1468 case EShLangIntersectNV:
1469 case EShLangAnyHitNV:
1470 case EShLangClosestHitNV:
1471 case EShLangMissNV:
1472 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001473 builder.addCapability(spv::CapabilityRayTracingNV);
1474 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001475 break;
Chao Chen3c366992018-09-19 11:41:59 -07001476 case EShLangTaskNV:
1477 case EShLangMeshNV:
1478 builder.addCapability(spv::CapabilityMeshShadingNV);
1479 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1480 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1481 glslangIntermediate->getLocalSize(1),
1482 glslangIntermediate->getLocalSize(2));
1483 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1485 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1486
1487 switch (glslangIntermediate->getOutputPrimitive()) {
1488 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1489 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1490 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1491 default: mode = spv::ExecutionModeMax; break;
1492 }
1493 if (mode != spv::ExecutionModeMax)
1494 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1495 }
1496 break;
1497#endif
1498
John Kessenich140f3df2015-06-26 16:58:36 -06001499 default:
1500 break;
1501 }
John Kessenich140f3df2015-06-26 16:58:36 -06001502}
1503
John Kessenichfca82622016-11-26 13:23:20 -07001504// Finish creating SPV, after the traversal is complete.
1505void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001506{
John Kessenichf04c51b2018-08-03 15:56:12 -06001507 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001508 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001509 builder.setBuildPoint(shaderEntry->getLastBlock());
1510 builder.leaveFunction();
1511 }
1512
John Kessenich7ba63412015-12-20 17:37:07 -07001513 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001514 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1515 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001516
John Kessenichf04c51b2018-08-03 15:56:12 -06001517 // Add capabilities, extensions, remove unneeded decorations, etc.,
1518 // based on the resulting SPIR-V.
1519 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001520}
1521
John Kessenichfca82622016-11-26 13:23:20 -07001522// Write the SPV into 'out'.
1523void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001524{
John Kessenichfca82622016-11-26 13:23:20 -07001525 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001526}
1527
1528//
1529// Implement the traversal functions.
1530//
1531// Return true from interior nodes to have the external traversal
1532// continue on to children. Return false if children were
1533// already processed.
1534//
1535
1536//
qining25262b32016-05-06 17:25:16 -04001537// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001538// - uniform/input reads
1539// - output writes
1540// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1541// - something simple that degenerates into the last bullet
1542//
1543void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1544{
qining75d1d802016-04-06 14:42:01 -04001545 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1546 if (symbol->getType().getQualifier().isSpecConstant())
1547 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1548
John Kessenich140f3df2015-06-26 16:58:36 -06001549 // getSymbolId() will set up all the IO decorations on the first call.
1550 // Formal function parameters were mapped during makeFunctions().
1551 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001552
1553 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1554 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001555 // Consider adding to the OpEntryPoint interface list.
1556 // Only looking at structures if they have at least one member.
1557 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1558 spv::StorageClass sc = builder.getStorageClass(id);
1559 // Before SPIR-V 1.4, we only want to include Input and Output.
1560 // Starting with SPIR-V 1.4, we want all globals.
1561 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1562 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001563 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001564 }
John Kessenich5f77d862017-09-19 11:09:59 -06001565 }
John Kessenich7ba63412015-12-20 17:37:07 -07001566 }
1567
1568 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001569 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001570 // Prepare to generate code for the access
1571
1572 // L-value chains will be computed left to right. We're on the symbol now,
1573 // which is the left-most part of the access chain, so now is "clear" time,
1574 // followed by setting the base.
1575 builder.clearAccessChain();
1576
1577 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001578 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001579 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001580 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001581 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001582 // These are also pure R-values.
1583 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001584 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001585 builder.setAccessChainRValue(id);
1586 else
1587 builder.setAccessChainLValue(id);
1588 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001589
1590 // Process linkage-only nodes for any special additional interface work.
1591 if (linkageOnly) {
1592 if (glslangIntermediate->getHlslFunctionality1()) {
1593 // Map implicit counter buffers to their originating buffers, which should have been
1594 // seen by now, given earlier pruning of unused counters, and preservation of order
1595 // of declaration.
1596 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1597 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1598 // Save possible originating buffers for counter buffers, keyed by
1599 // making the potential counter-buffer name.
1600 std::string keyName = symbol->getName().c_str();
1601 keyName = glslangIntermediate->addCounterBufferName(keyName);
1602 counterOriginator[keyName] = symbol;
1603 } else {
1604 // Handle a counter buffer, by finding the saved originating buffer.
1605 std::string keyName = symbol->getName().c_str();
1606 auto it = counterOriginator.find(keyName);
1607 if (it != counterOriginator.end()) {
1608 id = getSymbolId(it->second);
1609 if (id != spv::NoResult) {
1610 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001611 if (counterId != spv::NoResult) {
1612 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001613 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001614 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001615 }
1616 }
1617 }
1618 }
1619 }
1620 }
John Kessenich140f3df2015-06-26 16:58:36 -06001621}
1622
1623bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1624{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001625 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001626
qining40887662016-04-03 22:20:42 -04001627 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1628 if (node->getType().getQualifier().isSpecConstant())
1629 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1630
John Kessenich140f3df2015-06-26 16:58:36 -06001631 // First, handle special cases
1632 switch (node->getOp()) {
1633 case glslang::EOpAssign:
1634 case glslang::EOpAddAssign:
1635 case glslang::EOpSubAssign:
1636 case glslang::EOpMulAssign:
1637 case glslang::EOpVectorTimesMatrixAssign:
1638 case glslang::EOpVectorTimesScalarAssign:
1639 case glslang::EOpMatrixTimesScalarAssign:
1640 case glslang::EOpMatrixTimesMatrixAssign:
1641 case glslang::EOpDivAssign:
1642 case glslang::EOpModAssign:
1643 case glslang::EOpAndAssign:
1644 case glslang::EOpInclusiveOrAssign:
1645 case glslang::EOpExclusiveOrAssign:
1646 case glslang::EOpLeftShiftAssign:
1647 case glslang::EOpRightShiftAssign:
1648 // A bin-op assign "a += b" means the same thing as "a = a + b"
1649 // where a is evaluated before b. For a simple assignment, GLSL
1650 // says to evaluate the left before the right. So, always, left
1651 // node then right node.
1652 {
1653 // get the left l-value, save it away
1654 builder.clearAccessChain();
1655 node->getLeft()->traverse(this);
1656 spv::Builder::AccessChain lValue = builder.getAccessChain();
1657
1658 // evaluate the right
1659 builder.clearAccessChain();
1660 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001661 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001662
1663 if (node->getOp() != glslang::EOpAssign) {
1664 // the left is also an r-value
1665 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001666 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001667
1668 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001669 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001670 TranslateNoContractionDecoration(node->getType().getQualifier()),
1671 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001672 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001673 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1674 node->getType().getBasicType());
1675
1676 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001677 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 }
1679
1680 // store the result
1681 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001682 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001683
1684 // assignments are expressions having an rValue after they are evaluated...
1685 builder.clearAccessChain();
1686 builder.setAccessChainRValue(rValue);
1687 }
1688 return false;
1689 case glslang::EOpIndexDirect:
1690 case glslang::EOpIndexDirectStruct:
1691 {
1692 // Get the left part of the access chain.
1693 node->getLeft()->traverse(this);
1694
1695 // Add the next element in the chain
1696
David Netoa901ffe2016-06-08 14:11:40 +01001697 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001698 if (! node->getLeft()->getType().isArray() &&
1699 node->getLeft()->getType().isVector() &&
1700 node->getOp() == glslang::EOpIndexDirect) {
1701 // This is essentially a hard-coded vector swizzle of size 1,
1702 // so short circuit the access-chain stuff with a swizzle.
1703 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001704 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001705 int dummySize;
1706 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1707 TranslateCoherent(node->getLeft()->getType()),
1708 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001709 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001710
1711 // Load through a block reference is performed with a dot operator that
1712 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1713 // do a load and reset the access chain.
1714 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1715 !node->getLeft()->getType().isArray() &&
1716 node->getOp() == glslang::EOpIndexDirectStruct)
1717 {
1718 spv::Id left = accessChainLoad(node->getLeft()->getType());
1719 builder.clearAccessChain();
1720 builder.setAccessChainLValue(left);
1721 }
1722
David Netoa901ffe2016-06-08 14:11:40 +01001723 int spvIndex = glslangIndex;
1724 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1725 node->getOp() == glslang::EOpIndexDirectStruct)
1726 {
1727 // This may be, e.g., an anonymous block-member selection, which generally need
1728 // index remapping due to hidden members in anonymous blocks.
1729 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1730 assert(remapper.size() > 0);
1731 spvIndex = remapper[glslangIndex];
1732 }
John Kessenichebb50532016-05-16 19:22:05 -06001733
David Netoa901ffe2016-06-08 14:11:40 +01001734 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001735 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001736
1737 // Add capabilities here for accessing PointSize and clip/cull distance.
1738 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001739 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001740 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742 }
1743 return false;
1744 case glslang::EOpIndexIndirect:
1745 {
1746 // Structure or array or vector indirection.
1747 // Will use native SPIR-V access-chain for struct and array indirection;
1748 // matrices are arrays of vectors, so will also work for a matrix.
1749 // Will use the access chain's 'component' for variable index into a vector.
1750
1751 // This adapter is building access chains left to right.
1752 // Set up the access chain to the left.
1753 node->getLeft()->traverse(this);
1754
1755 // save it so that computing the right side doesn't trash it
1756 spv::Builder::AccessChain partial = builder.getAccessChain();
1757
1758 // compute the next index in the chain
1759 builder.clearAccessChain();
1760 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001761 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001762
John Kessenich5611c6d2018-04-05 11:25:02 -06001763 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1764
John Kessenich140f3df2015-06-26 16:58:36 -06001765 // restore the saved access chain
1766 builder.setAccessChain(partial);
1767
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001768 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1769 int dummySize;
1770 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1771 TranslateCoherent(node->getLeft()->getType()),
1772 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1773 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001774 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001775 }
1776 return false;
1777 case glslang::EOpVectorSwizzle:
1778 {
1779 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001780 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001781 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001782 int dummySize;
1783 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1784 TranslateCoherent(node->getLeft()->getType()),
1785 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001786 }
1787 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001788 case glslang::EOpMatrixSwizzle:
1789 logger->missingFunctionality("matrix swizzle");
1790 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001791 case glslang::EOpLogicalOr:
1792 case glslang::EOpLogicalAnd:
1793 {
1794
1795 // These may require short circuiting, but can sometimes be done as straight
1796 // binary operations. The right operand must be short circuited if it has
1797 // side effects, and should probably be if it is complex.
1798 if (isTrivial(node->getRight()->getAsTyped()))
1799 break; // handle below as a normal binary operation
1800 // otherwise, we need to do dynamic short circuiting on the right operand
1801 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1802 builder.clearAccessChain();
1803 builder.setAccessChainRValue(result);
1804 }
1805 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001806 default:
1807 break;
1808 }
1809
1810 // Assume generic binary op...
1811
John Kessenich32cfd492016-02-02 12:37:46 -07001812 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001813 builder.clearAccessChain();
1814 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001815 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001816
John Kessenich32cfd492016-02-02 12:37:46 -07001817 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001818 builder.clearAccessChain();
1819 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001820 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001821
John Kessenich32cfd492016-02-02 12:37:46 -07001822 // get result
John Kessenichead86222018-03-28 18:01:20 -06001823 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001824 TranslateNoContractionDecoration(node->getType().getQualifier()),
1825 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001826 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001827 convertGlslangToSpvType(node->getType()), left, right,
1828 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001829
John Kessenich50e57562015-12-21 21:21:11 -07001830 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001831 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001832 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001833 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001834 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001835 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001836 return false;
1837 }
John Kessenich140f3df2015-06-26 16:58:36 -06001838}
1839
1840bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1841{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001842 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001843
qining40887662016-04-03 22:20:42 -04001844 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1845 if (node->getType().getQualifier().isSpecConstant())
1846 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1847
John Kessenichfc51d282015-08-19 13:34:18 -06001848 spv::Id result = spv::NoResult;
1849
1850 // try texturing first
1851 result = createImageTextureFunctionCall(node);
1852 if (result != spv::NoResult) {
1853 builder.clearAccessChain();
1854 builder.setAccessChainRValue(result);
1855
1856 return false; // done with this node
1857 }
1858
1859 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001860
1861 if (node->getOp() == glslang::EOpArrayLength) {
1862 // Quite special; won't want to evaluate the operand.
1863
John Kessenich5611c6d2018-04-05 11:25:02 -06001864 // Currently, the front-end does not allow .length() on an array until it is sized,
1865 // except for the last block membeor of an SSBO.
1866 // TODO: If this changes, link-time sized arrays might show up here, and need their
1867 // size extracted.
1868
John Kessenichc9a80832015-09-12 12:17:44 -06001869 // Normal .length() would have been constant folded by the front-end.
1870 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001871 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001872
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001873 spv::Id length;
1874 if (node->getOperand()->getType().isCoopMat()) {
1875 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1876
1877 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1878 assert(builder.isCooperativeMatrixType(typeId));
1879
1880 length = builder.createCooperativeMatrixLength(typeId);
1881 } else {
1882 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1883 block->traverse(this);
1884 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1885 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1886 }
John Kessenichc9a80832015-09-12 12:17:44 -06001887
John Kessenich8c869672018-11-28 07:01:37 -07001888 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1889 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1890 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001891 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1892 if (builder.isInSpecConstCodeGenMode()) {
1893 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1894 } else {
1895 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1896 }
1897 }
John Kessenich8c869672018-11-28 07:01:37 -07001898
John Kessenichc9a80832015-09-12 12:17:44 -06001899 builder.clearAccessChain();
1900 builder.setAccessChainRValue(length);
1901
1902 return false;
1903 }
1904
John Kessenichfc51d282015-08-19 13:34:18 -06001905 // Start by evaluating the operand
1906
John Kessenich8c8505c2016-07-26 12:50:38 -06001907 // Does it need a swizzle inversion? If so, evaluation is inverted;
1908 // operate first on the swizzle base, then apply the swizzle.
1909 spv::Id invertedType = spv::NoType;
1910 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1911 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1912 invertedType = getInvertedSwizzleType(*node->getOperand());
1913
John Kessenich140f3df2015-06-26 16:58:36 -06001914 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001915 if (invertedType != spv::NoType)
1916 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1917 else
1918 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001919
Rex Xufc618912015-09-09 16:42:49 +08001920 spv::Id operand = spv::NoResult;
1921
1922 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1923 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001924 node->getOp() == glslang::EOpAtomicCounter ||
1925 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001926 operand = builder.accessChainGetLValue(); // Special case l-value operands
1927 else
John Kessenich32cfd492016-02-02 12:37:46 -07001928 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001929
John Kessenichead86222018-03-28 18:01:20 -06001930 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001931 TranslateNoContractionDecoration(node->getType().getQualifier()),
1932 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001933
1934 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001935 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001936 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001937
1938 // if not, then possibly an operation
1939 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001940 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001941
1942 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001943 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001944 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001945 builder.addDecoration(result, decorations.nonUniform);
1946 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001947
John Kessenich140f3df2015-06-26 16:58:36 -06001948 builder.clearAccessChain();
1949 builder.setAccessChainRValue(result);
1950
1951 return false; // done with this node
1952 }
1953
1954 // it must be a special case, check...
1955 switch (node->getOp()) {
1956 case glslang::EOpPostIncrement:
1957 case glslang::EOpPostDecrement:
1958 case glslang::EOpPreIncrement:
1959 case glslang::EOpPreDecrement:
1960 {
1961 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001962 spv::Id one = 0;
1963 if (node->getBasicType() == glslang::EbtFloat)
1964 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001965 else if (node->getBasicType() == glslang::EbtDouble)
1966 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001967 else if (node->getBasicType() == glslang::EbtFloat16)
1968 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001969 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1970 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001971 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1972 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001973 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1974 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001975 else
1976 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001977 glslang::TOperator op;
1978 if (node->getOp() == glslang::EOpPreIncrement ||
1979 node->getOp() == glslang::EOpPostIncrement)
1980 op = glslang::EOpAdd;
1981 else
1982 op = glslang::EOpSub;
1983
John Kessenichead86222018-03-28 18:01:20 -06001984 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001985 convertGlslangToSpvType(node->getType()), operand, one,
1986 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001987 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001988
1989 // The result of operation is always stored, but conditionally the
1990 // consumed result. The consumed result is always an r-value.
1991 builder.accessChainStore(result);
1992 builder.clearAccessChain();
1993 if (node->getOp() == glslang::EOpPreIncrement ||
1994 node->getOp() == glslang::EOpPreDecrement)
1995 builder.setAccessChainRValue(result);
1996 else
1997 builder.setAccessChainRValue(operand);
1998 }
1999
2000 return false;
2001
2002 case glslang::EOpEmitStreamVertex:
2003 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2004 return false;
2005 case glslang::EOpEndStreamPrimitive:
2006 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2007 return false;
2008
2009 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002010 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002011 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002012 }
John Kessenich140f3df2015-06-26 16:58:36 -06002013}
2014
2015bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2016{
qining27e04a02016-04-14 16:40:20 -04002017 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2018 if (node->getType().getQualifier().isSpecConstant())
2019 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2020
John Kessenichfc51d282015-08-19 13:34:18 -06002021 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002022 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2023 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002024
2025 // try texturing
2026 result = createImageTextureFunctionCall(node);
2027 if (result != spv::NoResult) {
2028 builder.clearAccessChain();
2029 builder.setAccessChainRValue(result);
2030
2031 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002032 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002033#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002034 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002035#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002036 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002037 // "imageStore" is a special case, which has no result
2038 return false;
2039 }
John Kessenichfc51d282015-08-19 13:34:18 -06002040
John Kessenich140f3df2015-06-26 16:58:36 -06002041 glslang::TOperator binOp = glslang::EOpNull;
2042 bool reduceComparison = true;
2043 bool isMatrix = false;
2044 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002045 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002046
2047 assert(node->getOp());
2048
John Kessenichf6640762016-08-01 19:44:00 -06002049 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002050
2051 switch (node->getOp()) {
2052 case glslang::EOpSequence:
2053 {
2054 if (preVisit)
2055 ++sequenceDepth;
2056 else
2057 --sequenceDepth;
2058
2059 if (sequenceDepth == 1) {
2060 // If this is the parent node of all the functions, we want to see them
2061 // early, so all call points have actual SPIR-V functions to reference.
2062 // In all cases, still let the traverser visit the children for us.
2063 makeFunctions(node->getAsAggregate()->getSequence());
2064
John Kessenich6fccb3c2016-09-19 16:01:41 -06002065 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002066 // anything else gets there, so visit out of order, doing them all now.
2067 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2068
John Kessenich6a60c2f2016-12-08 21:01:59 -07002069 // 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 -06002070 // so do them manually.
2071 visitFunctions(node->getAsAggregate()->getSequence());
2072
2073 return false;
2074 }
2075
2076 return true;
2077 }
2078 case glslang::EOpLinkerObjects:
2079 {
2080 if (visit == glslang::EvPreVisit)
2081 linkageOnly = true;
2082 else
2083 linkageOnly = false;
2084
2085 return true;
2086 }
2087 case glslang::EOpComma:
2088 {
2089 // processing from left to right naturally leaves the right-most
2090 // lying around in the access chain
2091 glslang::TIntermSequence& glslangOperands = node->getSequence();
2092 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2093 glslangOperands[i]->traverse(this);
2094
2095 return false;
2096 }
2097 case glslang::EOpFunction:
2098 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002099 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002100 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002101 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002102 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002103 } else {
2104 handleFunctionEntry(node);
2105 }
2106 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002107 if (inEntryPoint)
2108 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002109 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002110 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002111 }
2112
2113 return true;
2114 case glslang::EOpParameters:
2115 // Parameters will have been consumed by EOpFunction processing, but not
2116 // the body, so we still visited the function node's children, making this
2117 // child redundant.
2118 return false;
2119 case glslang::EOpFunctionCall:
2120 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002122 if (node->isUserDefined())
2123 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002124 // 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 -07002125 if (result) {
2126 builder.clearAccessChain();
2127 builder.setAccessChainRValue(result);
2128 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002129 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002130
2131 return false;
2132 }
2133 case glslang::EOpConstructMat2x2:
2134 case glslang::EOpConstructMat2x3:
2135 case glslang::EOpConstructMat2x4:
2136 case glslang::EOpConstructMat3x2:
2137 case glslang::EOpConstructMat3x3:
2138 case glslang::EOpConstructMat3x4:
2139 case glslang::EOpConstructMat4x2:
2140 case glslang::EOpConstructMat4x3:
2141 case glslang::EOpConstructMat4x4:
2142 case glslang::EOpConstructDMat2x2:
2143 case glslang::EOpConstructDMat2x3:
2144 case glslang::EOpConstructDMat2x4:
2145 case glslang::EOpConstructDMat3x2:
2146 case glslang::EOpConstructDMat3x3:
2147 case glslang::EOpConstructDMat3x4:
2148 case glslang::EOpConstructDMat4x2:
2149 case glslang::EOpConstructDMat4x3:
2150 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002151 case glslang::EOpConstructIMat2x2:
2152 case glslang::EOpConstructIMat2x3:
2153 case glslang::EOpConstructIMat2x4:
2154 case glslang::EOpConstructIMat3x2:
2155 case glslang::EOpConstructIMat3x3:
2156 case glslang::EOpConstructIMat3x4:
2157 case glslang::EOpConstructIMat4x2:
2158 case glslang::EOpConstructIMat4x3:
2159 case glslang::EOpConstructIMat4x4:
2160 case glslang::EOpConstructUMat2x2:
2161 case glslang::EOpConstructUMat2x3:
2162 case glslang::EOpConstructUMat2x4:
2163 case glslang::EOpConstructUMat3x2:
2164 case glslang::EOpConstructUMat3x3:
2165 case glslang::EOpConstructUMat3x4:
2166 case glslang::EOpConstructUMat4x2:
2167 case glslang::EOpConstructUMat4x3:
2168 case glslang::EOpConstructUMat4x4:
2169 case glslang::EOpConstructBMat2x2:
2170 case glslang::EOpConstructBMat2x3:
2171 case glslang::EOpConstructBMat2x4:
2172 case glslang::EOpConstructBMat3x2:
2173 case glslang::EOpConstructBMat3x3:
2174 case glslang::EOpConstructBMat3x4:
2175 case glslang::EOpConstructBMat4x2:
2176 case glslang::EOpConstructBMat4x3:
2177 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002178 case glslang::EOpConstructF16Mat2x2:
2179 case glslang::EOpConstructF16Mat2x3:
2180 case glslang::EOpConstructF16Mat2x4:
2181 case glslang::EOpConstructF16Mat3x2:
2182 case glslang::EOpConstructF16Mat3x3:
2183 case glslang::EOpConstructF16Mat3x4:
2184 case glslang::EOpConstructF16Mat4x2:
2185 case glslang::EOpConstructF16Mat4x3:
2186 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002187 isMatrix = true;
2188 // fall through
2189 case glslang::EOpConstructFloat:
2190 case glslang::EOpConstructVec2:
2191 case glslang::EOpConstructVec3:
2192 case glslang::EOpConstructVec4:
2193 case glslang::EOpConstructDouble:
2194 case glslang::EOpConstructDVec2:
2195 case glslang::EOpConstructDVec3:
2196 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002197 case glslang::EOpConstructFloat16:
2198 case glslang::EOpConstructF16Vec2:
2199 case glslang::EOpConstructF16Vec3:
2200 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002201 case glslang::EOpConstructBool:
2202 case glslang::EOpConstructBVec2:
2203 case glslang::EOpConstructBVec3:
2204 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002205 case glslang::EOpConstructInt8:
2206 case glslang::EOpConstructI8Vec2:
2207 case glslang::EOpConstructI8Vec3:
2208 case glslang::EOpConstructI8Vec4:
2209 case glslang::EOpConstructUint8:
2210 case glslang::EOpConstructU8Vec2:
2211 case glslang::EOpConstructU8Vec3:
2212 case glslang::EOpConstructU8Vec4:
2213 case glslang::EOpConstructInt16:
2214 case glslang::EOpConstructI16Vec2:
2215 case glslang::EOpConstructI16Vec3:
2216 case glslang::EOpConstructI16Vec4:
2217 case glslang::EOpConstructUint16:
2218 case glslang::EOpConstructU16Vec2:
2219 case glslang::EOpConstructU16Vec3:
2220 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002221 case glslang::EOpConstructInt:
2222 case glslang::EOpConstructIVec2:
2223 case glslang::EOpConstructIVec3:
2224 case glslang::EOpConstructIVec4:
2225 case glslang::EOpConstructUint:
2226 case glslang::EOpConstructUVec2:
2227 case glslang::EOpConstructUVec3:
2228 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002229 case glslang::EOpConstructInt64:
2230 case glslang::EOpConstructI64Vec2:
2231 case glslang::EOpConstructI64Vec3:
2232 case glslang::EOpConstructI64Vec4:
2233 case glslang::EOpConstructUint64:
2234 case glslang::EOpConstructU64Vec2:
2235 case glslang::EOpConstructU64Vec3:
2236 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002237 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002238 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002239 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002240 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002241 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002242 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002243 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002244 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002245 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002246 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002247 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002248 else if (node->getOp() == glslang::EOpConstructStruct ||
2249 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2250 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002251 std::vector<spv::Id> constituents;
2252 for (int c = 0; c < (int)arguments.size(); ++c)
2253 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002254 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002255 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002256 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002257 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002259
2260 builder.clearAccessChain();
2261 builder.setAccessChainRValue(constructed);
2262
2263 return false;
2264 }
2265
2266 // These six are component-wise compares with component-wise results.
2267 // Forward on to createBinaryOperation(), requesting a vector result.
2268 case glslang::EOpLessThan:
2269 case glslang::EOpGreaterThan:
2270 case glslang::EOpLessThanEqual:
2271 case glslang::EOpGreaterThanEqual:
2272 case glslang::EOpVectorEqual:
2273 case glslang::EOpVectorNotEqual:
2274 {
2275 // Map the operation to a binary
2276 binOp = node->getOp();
2277 reduceComparison = false;
2278 switch (node->getOp()) {
2279 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2280 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2281 default: binOp = node->getOp(); break;
2282 }
2283
2284 break;
2285 }
2286 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002287 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002288 binOp = glslang::EOpMul;
2289 break;
2290 case glslang::EOpOuterProduct:
2291 // two vectors multiplied to make a matrix
2292 binOp = glslang::EOpOuterProduct;
2293 break;
2294 case glslang::EOpDot:
2295 {
qining25262b32016-05-06 17:25:16 -04002296 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002297 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002298 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002299 binOp = glslang::EOpMul;
2300 break;
2301 }
2302 case glslang::EOpMod:
2303 // when an aggregate, this is the floating-point mod built-in function,
2304 // which can be emitted by the one in createBinaryOperation()
2305 binOp = glslang::EOpMod;
2306 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002307 case glslang::EOpEmitVertex:
2308 case glslang::EOpEndPrimitive:
2309 case glslang::EOpBarrier:
2310 case glslang::EOpMemoryBarrier:
2311 case glslang::EOpMemoryBarrierAtomicCounter:
2312 case glslang::EOpMemoryBarrierBuffer:
2313 case glslang::EOpMemoryBarrierImage:
2314 case glslang::EOpMemoryBarrierShared:
2315 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002316 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002317 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002318 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002319 case glslang::EOpWorkgroupMemoryBarrier:
2320 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002321 case glslang::EOpSubgroupBarrier:
2322 case glslang::EOpSubgroupMemoryBarrier:
2323 case glslang::EOpSubgroupMemoryBarrierBuffer:
2324 case glslang::EOpSubgroupMemoryBarrierImage:
2325 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002326 noReturnValue = true;
2327 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2328 break;
2329
Jeff Bolz36831c92018-09-05 10:11:41 -05002330 case glslang::EOpAtomicStore:
2331 noReturnValue = true;
2332 // fallthrough
2333 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002334 case glslang::EOpAtomicAdd:
2335 case glslang::EOpAtomicMin:
2336 case glslang::EOpAtomicMax:
2337 case glslang::EOpAtomicAnd:
2338 case glslang::EOpAtomicOr:
2339 case glslang::EOpAtomicXor:
2340 case glslang::EOpAtomicExchange:
2341 case glslang::EOpAtomicCompSwap:
2342 atomic = true;
2343 break;
2344
John Kessenich0d0c6d32017-07-23 16:08:26 -06002345 case glslang::EOpAtomicCounterAdd:
2346 case glslang::EOpAtomicCounterSubtract:
2347 case glslang::EOpAtomicCounterMin:
2348 case glslang::EOpAtomicCounterMax:
2349 case glslang::EOpAtomicCounterAnd:
2350 case glslang::EOpAtomicCounterOr:
2351 case glslang::EOpAtomicCounterXor:
2352 case glslang::EOpAtomicCounterExchange:
2353 case glslang::EOpAtomicCounterCompSwap:
2354 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2355 builder.addCapability(spv::CapabilityAtomicStorageOps);
2356 atomic = true;
2357 break;
2358
Chao Chen3c366992018-09-19 11:41:59 -07002359#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002360 case glslang::EOpIgnoreIntersectionNV:
2361 case glslang::EOpTerminateRayNV:
2362 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002363 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002364 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2365 noReturnValue = true;
2366 break;
2367#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002368 case glslang::EOpCooperativeMatrixLoad:
2369 case glslang::EOpCooperativeMatrixStore:
2370 noReturnValue = true;
2371 break;
Chao Chen3c366992018-09-19 11:41:59 -07002372
John Kessenich140f3df2015-06-26 16:58:36 -06002373 default:
2374 break;
2375 }
2376
2377 //
2378 // See if it maps to a regular operation.
2379 //
John Kessenich140f3df2015-06-26 16:58:36 -06002380 if (binOp != glslang::EOpNull) {
2381 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2382 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2383 assert(left && right);
2384
2385 builder.clearAccessChain();
2386 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002387 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002388
2389 builder.clearAccessChain();
2390 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002391 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002392
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002393 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002394 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002395 TranslateNoContractionDecoration(node->getType().getQualifier()),
2396 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002397 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002398 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002399 left->getType().getBasicType(), reduceComparison);
2400
2401 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002402 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002403 builder.clearAccessChain();
2404 builder.setAccessChainRValue(result);
2405
2406 return false;
2407 }
2408
John Kessenich426394d2015-07-23 10:22:48 -06002409 //
2410 // Create the list of operands.
2411 //
John Kessenich140f3df2015-06-26 16:58:36 -06002412 glslang::TIntermSequence& glslangOperands = node->getSequence();
2413 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002414 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002415 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002416 // special case l-value operands; there are just a few
2417 bool lvalue = false;
2418 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002419 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002420 case glslang::EOpModf:
2421 if (arg == 1)
2422 lvalue = true;
2423 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002424 case glslang::EOpInterpolateAtSample:
2425 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002426#ifdef AMD_EXTENSIONS
2427 case glslang::EOpInterpolateAtVertex:
2428#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002429 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002430 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002431
2432 // Does it need a swizzle inversion? If so, evaluation is inverted;
2433 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002434 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002435 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2436 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2437 }
Rex Xu7a26c172015-12-08 17:12:09 +08002438 break;
Rex Xud4782c12015-09-06 16:30:11 +08002439 case glslang::EOpAtomicAdd:
2440 case glslang::EOpAtomicMin:
2441 case glslang::EOpAtomicMax:
2442 case glslang::EOpAtomicAnd:
2443 case glslang::EOpAtomicOr:
2444 case glslang::EOpAtomicXor:
2445 case glslang::EOpAtomicExchange:
2446 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002447 case glslang::EOpAtomicLoad:
2448 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002449 case glslang::EOpAtomicCounterAdd:
2450 case glslang::EOpAtomicCounterSubtract:
2451 case glslang::EOpAtomicCounterMin:
2452 case glslang::EOpAtomicCounterMax:
2453 case glslang::EOpAtomicCounterAnd:
2454 case glslang::EOpAtomicCounterOr:
2455 case glslang::EOpAtomicCounterXor:
2456 case glslang::EOpAtomicCounterExchange:
2457 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002458 if (arg == 0)
2459 lvalue = true;
2460 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002461 case glslang::EOpAddCarry:
2462 case glslang::EOpSubBorrow:
2463 if (arg == 2)
2464 lvalue = true;
2465 break;
2466 case glslang::EOpUMulExtended:
2467 case glslang::EOpIMulExtended:
2468 if (arg >= 2)
2469 lvalue = true;
2470 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002471 case glslang::EOpCooperativeMatrixLoad:
2472 if (arg == 0 || arg == 1)
2473 lvalue = true;
2474 break;
2475 case glslang::EOpCooperativeMatrixStore:
2476 if (arg == 1)
2477 lvalue = true;
2478 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002479 default:
2480 break;
2481 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002482 builder.clearAccessChain();
2483 if (invertedType != spv::NoType && arg == 0)
2484 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2485 else
2486 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002487
2488 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2489 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2490
2491 if (arg == 1) {
2492 // fold "element" parameter into the access chain
2493 spv::Builder::AccessChain save = builder.getAccessChain();
2494 builder.clearAccessChain();
2495 glslangOperands[2]->traverse(this);
2496
2497 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2498
2499 builder.setAccessChain(save);
2500
2501 // Point to the first element of the array.
2502 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002503 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002504
2505 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2506 unsigned int alignment = builder.getAccessChain().alignment;
2507
2508 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2509 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2510 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2511 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2512 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2513 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2514 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2515 }
2516
2517 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2518
2519 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2520 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2521 }
2522
2523 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2524 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2525 }
2526 } else if (arg == 2) {
2527 continue;
2528 }
2529 }
2530
John Kessenich140f3df2015-06-26 16:58:36 -06002531 if (lvalue)
2532 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002533 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002534 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002535 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002536 }
John Kessenich140f3df2015-06-26 16:58:36 -06002537 }
John Kessenich426394d2015-07-23 10:22:48 -06002538
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002539 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002540 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2541 std::vector<spv::IdImmediate> idImmOps;
2542
2543 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2544 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2545 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2546 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2547 // get the pointee type
2548 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2549 assert(builder.isCooperativeMatrixType(typeId));
2550 // do the op
2551 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2552 // store the result to the pointer (out param 'm')
2553 builder.createStore(result, operands[0]);
2554 result = 0;
2555 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2556 std::vector<spv::IdImmediate> idImmOps;
2557
2558 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2559 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2560 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2561 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2562 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2563
2564 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2565 result = 0;
2566 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002567 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002568 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002569 } else {
2570 // Pass through to generic operations.
2571 switch (glslangOperands.size()) {
2572 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002573 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002574 break;
2575 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002576 {
2577 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002578 TranslateNoContractionDecoration(node->getType().getQualifier()),
2579 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002580 result = createUnaryOperation(
2581 node->getOp(), decorations,
2582 resultType(), operands.front(),
2583 glslangOperands[0]->getAsTyped()->getBasicType());
2584 }
John Kessenich426394d2015-07-23 10:22:48 -06002585 break;
2586 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002587 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002588 break;
2589 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 if (invertedType)
2591 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002592 }
2593
2594 if (noReturnValue)
2595 return false;
2596
2597 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002598 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002599 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002600 } else {
2601 builder.clearAccessChain();
2602 builder.setAccessChainRValue(result);
2603 return false;
2604 }
2605}
2606
John Kessenich433e9ff2017-01-26 20:31:11 -07002607// This path handles both if-then-else and ?:
2608// The if-then-else has a node type of void, while
2609// ?: has either a void or a non-void node type
2610//
2611// Leaving the result, when not void:
2612// GLSL only has r-values as the result of a :?, but
2613// if we have an l-value, that can be more efficient if it will
2614// become the base of a complex r-value expression, because the
2615// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002616bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2617{
John Kessenich4bee5312018-02-20 21:29:05 -07002618 // See if it simple and safe, or required, to execute both sides.
2619 // Crucially, side effects must be either semantically required or avoided,
2620 // and there are performance trade-offs.
2621 // Return true if required or a good idea (and safe) to execute both sides,
2622 // false otherwise.
2623 const auto bothSidesPolicy = [&]() -> bool {
2624 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002625 if (node->getTrueBlock() == nullptr ||
2626 node->getFalseBlock() == nullptr)
2627 return false;
2628
John Kessenich4bee5312018-02-20 21:29:05 -07002629 // required? (unless we write additional code to look for side effects
2630 // and make performance trade-offs if none are present)
2631 if (!node->getShortCircuit())
2632 return true;
2633
2634 // if not required to execute both, decide based on performance/practicality...
2635
2636 // see if OpSelect can handle it
2637 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2638 node->getBasicType() == glslang::EbtVoid)
2639 return false;
2640
John Kessenich433e9ff2017-01-26 20:31:11 -07002641 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2642 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2643
2644 // return true if a single operand to ? : is okay for OpSelect
2645 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002646 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002647 };
2648
2649 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2650 operandOkay(node->getFalseBlock()->getAsTyped());
2651 };
2652
John Kessenich4bee5312018-02-20 21:29:05 -07002653 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2654 // emit the condition before doing anything with selection
2655 node->getCondition()->traverse(this);
2656 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2657
2658 // Find a way of executing both sides and selecting the right result.
2659 const auto executeBothSides = [&]() -> void {
2660 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002661 node->getTrueBlock()->traverse(this);
2662 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2663 node->getFalseBlock()->traverse(this);
2664 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2665
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002666 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002667
John Kessenich4bee5312018-02-20 21:29:05 -07002668 // done if void
2669 if (node->getBasicType() == glslang::EbtVoid)
2670 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002671
John Kessenich4bee5312018-02-20 21:29:05 -07002672 // emit code to select between trueValue and falseValue
2673
2674 // see if OpSelect can handle it
2675 if (node->getType().isScalar() || node->getType().isVector()) {
2676 // Emit OpSelect for this selection.
2677
2678 // smear condition to vector, if necessary (AST is always scalar)
2679 if (builder.isVector(trueValue))
2680 condition = builder.smearScalar(spv::NoPrecision, condition,
2681 builder.makeVectorType(builder.makeBoolType(),
2682 builder.getNumComponents(trueValue)));
2683
2684 // OpSelect
2685 result = builder.createTriOp(spv::OpSelect,
2686 convertGlslangToSpvType(node->getType()), condition,
2687 trueValue, falseValue);
2688
2689 builder.clearAccessChain();
2690 builder.setAccessChainRValue(result);
2691 } else {
2692 // We need control flow to select the result.
2693 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2694 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2695
2696 // Selection control:
2697 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2698
2699 // make an "if" based on the value created by the condition
2700 spv::Builder::If ifBuilder(condition, control, builder);
2701
2702 // emit the "then" statement
2703 builder.createStore(trueValue, result);
2704 ifBuilder.makeBeginElse();
2705 // emit the "else" statement
2706 builder.createStore(falseValue, result);
2707
2708 // finish off the control flow
2709 ifBuilder.makeEndIf();
2710
2711 builder.clearAccessChain();
2712 builder.setAccessChainLValue(result);
2713 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002714 };
2715
John Kessenich4bee5312018-02-20 21:29:05 -07002716 // Execute the one side needed, as per the condition
2717 const auto executeOneSide = [&]() {
2718 // Always emit control flow.
2719 if (node->getBasicType() != glslang::EbtVoid)
2720 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002721
John Kessenich4bee5312018-02-20 21:29:05 -07002722 // Selection control:
2723 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2724
2725 // make an "if" based on the value created by the condition
2726 spv::Builder::If ifBuilder(condition, control, builder);
2727
2728 // emit the "then" statement
2729 if (node->getTrueBlock() != nullptr) {
2730 node->getTrueBlock()->traverse(this);
2731 if (result != spv::NoResult)
2732 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2733 }
2734
2735 if (node->getFalseBlock() != nullptr) {
2736 ifBuilder.makeBeginElse();
2737 // emit the "else" statement
2738 node->getFalseBlock()->traverse(this);
2739 if (result != spv::NoResult)
2740 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2741 }
2742
2743 // finish off the control flow
2744 ifBuilder.makeEndIf();
2745
2746 if (result != spv::NoResult) {
2747 builder.clearAccessChain();
2748 builder.setAccessChainLValue(result);
2749 }
2750 };
2751
2752 // Try for OpSelect (or a requirement to execute both sides)
2753 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002754 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2755 if (node->getType().getQualifier().isSpecConstant())
2756 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002757 executeBothSides();
2758 } else
2759 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002760
2761 return false;
2762}
2763
2764bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2765{
2766 // emit and get the condition before doing anything with switch
2767 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002768 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002769
Rex Xu57e65922017-07-04 23:23:40 +08002770 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002771 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002772
John Kessenich140f3df2015-06-26 16:58:36 -06002773 // browse the children to sort out code segments
2774 int defaultSegment = -1;
2775 std::vector<TIntermNode*> codeSegments;
2776 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2777 std::vector<int> caseValues;
2778 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2779 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2780 TIntermNode* child = *c;
2781 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002782 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002783 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002784 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002785 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2786 } else
2787 codeSegments.push_back(child);
2788 }
2789
qining25262b32016-05-06 17:25:16 -04002790 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002791 // statements between the last case and the end of the switch statement
2792 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2793 (int)codeSegments.size() == defaultSegment)
2794 codeSegments.push_back(nullptr);
2795
2796 // make the switch statement
2797 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002798 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002799
2800 // emit all the code in the segments
2801 breakForLoop.push(false);
2802 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2803 builder.nextSwitchSegment(segmentBlocks, s);
2804 if (codeSegments[s])
2805 codeSegments[s]->traverse(this);
2806 else
2807 builder.addSwitchBreak();
2808 }
2809 breakForLoop.pop();
2810
2811 builder.endSwitch(segmentBlocks);
2812
2813 return false;
2814}
2815
2816void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2817{
2818 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002819 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002820
2821 builder.clearAccessChain();
2822 builder.setAccessChainRValue(constant);
2823}
2824
2825bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2826{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002827 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002828 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002829
2830 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002831 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2832 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002833
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002834 // Spec requires back edges to target header blocks, and every header block
2835 // must dominate its merge block. Make a header block first to ensure these
2836 // conditions are met. By definition, it will contain OpLoopMerge, followed
2837 // by a block-ending branch. But we don't want to put any other body/test
2838 // instructions in it, since the body/test may have arbitrary instructions,
2839 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002840 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002841 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002842 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002843 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002844 spv::Block& test = builder.makeNewBlock();
2845 builder.createBranch(&test);
2846
2847 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002848 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002849 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002850 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2851
2852 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002853 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002854 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002855 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002856 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002857 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002858
2859 builder.setBuildPoint(&blocks.continue_target);
2860 if (node->getTerminal())
2861 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002862 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002863 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002864 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002865 builder.createBranch(&blocks.body);
2866
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002867 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002868 builder.setBuildPoint(&blocks.body);
2869 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002870 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002871 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002872 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002873
2874 builder.setBuildPoint(&blocks.continue_target);
2875 if (node->getTerminal())
2876 node->getTerminal()->traverse(this);
2877 if (node->getTest()) {
2878 node->getTest()->traverse(this);
2879 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002880 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002881 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002882 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002883 // TODO: unless there was a break/return/discard instruction
2884 // somewhere in the body, this is an infinite loop, so we should
2885 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002886 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002887 }
John Kessenich140f3df2015-06-26 16:58:36 -06002888 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002889 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002890 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002891 return false;
2892}
2893
2894bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2895{
2896 if (node->getExpression())
2897 node->getExpression()->traverse(this);
2898
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002899 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002900
John Kessenich140f3df2015-06-26 16:58:36 -06002901 switch (node->getFlowOp()) {
2902 case glslang::EOpKill:
2903 builder.makeDiscard();
2904 break;
2905 case glslang::EOpBreak:
2906 if (breakForLoop.top())
2907 builder.createLoopExit();
2908 else
2909 builder.addSwitchBreak();
2910 break;
2911 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002912 builder.createLoopContinue();
2913 break;
2914 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002915 if (node->getExpression()) {
2916 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2917 spv::Id returnId = accessChainLoad(glslangReturnType);
2918 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2919 builder.clearAccessChain();
2920 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2921 builder.setAccessChainLValue(copyId);
2922 multiTypeStore(glslangReturnType, returnId);
2923 returnId = builder.createLoad(copyId);
2924 }
2925 builder.makeReturn(false, returnId);
2926 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002927 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002928
2929 builder.clearAccessChain();
2930 break;
2931
2932 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002933 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002934 break;
2935 }
2936
2937 return false;
2938}
2939
2940spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2941{
qining25262b32016-05-06 17:25:16 -04002942 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002943 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002944 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002945 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002946 spv::Id result = createSpvConstant(*node);
2947 if (result != spv::NoResult)
2948 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002949 }
2950
2951 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002952 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002953 spv::Id spvType = convertGlslangToSpvType(node->getType());
2954
Rex Xucabbb782017-03-24 13:41:14 +08002955 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2956 node->getType().containsBasicType(glslang::EbtInt16) ||
2957 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002958 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002959 switch (storageClass) {
2960 case spv::StorageClassInput:
2961 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002962 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002963 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002964 break;
2965 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002966 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002967 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002968 break;
2969 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002970 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002971 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2972 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002973 else
2974 builder.addCapability(spv::CapabilityStorageUniform16);
2975 break;
2976 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002977 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002978 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2979 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2980 break;
2981 default:
2982 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002983 }
2984 }
Rex Xuf89ad982017-04-07 23:22:33 +08002985
John Kessenich312dcfb2018-07-03 13:19:51 -06002986 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2987 node->getType().containsBasicType(glslang::EbtUint8);
2988 if (contains8BitType) {
2989 if (storageClass == spv::StorageClassPushConstant) {
2990 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2991 builder.addCapability(spv::CapabilityStoragePushConstant8);
2992 } else if (storageClass == spv::StorageClassUniform) {
2993 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2994 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002995 } else if (storageClass == spv::StorageClassStorageBuffer) {
2996 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2997 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002998 }
2999 }
3000
John Kessenich140f3df2015-06-26 16:58:36 -06003001 const char* name = node->getName().c_str();
3002 if (glslang::IsAnonymous(name))
3003 name = "";
3004
3005 return builder.createVariable(storageClass, spvType, name);
3006}
3007
3008// Return type Id of the sampled type.
3009spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3010{
3011 switch (sampler.type) {
3012 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003013#ifdef AMD_EXTENSIONS
3014 case glslang::EbtFloat16:
3015 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3016 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3017 return builder.makeFloatType(16);
3018#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003019 case glslang::EbtInt: return builder.makeIntType(32);
3020 case glslang::EbtUint: return builder.makeUintType(32);
3021 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003022 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003023 return builder.makeFloatType(32);
3024 }
3025}
3026
John Kessenich8c8505c2016-07-26 12:50:38 -06003027// If node is a swizzle operation, return the type that should be used if
3028// the swizzle base is first consumed by another operation, before the swizzle
3029// is applied.
3030spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3031{
John Kessenichecba76f2017-01-06 00:34:48 -07003032 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003033 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3034 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3035 else
3036 return spv::NoType;
3037}
3038
3039// When inverting a swizzle with a parent op, this function
3040// will apply the swizzle operation to a completed parent operation.
3041spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3042{
3043 std::vector<unsigned> swizzle;
3044 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3045 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3046}
3047
John Kessenich8c8505c2016-07-26 12:50:38 -06003048// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3049void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3050{
3051 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3052 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3053 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3054}
3055
John Kessenich3ac051e2015-12-20 11:29:16 -07003056// Convert from a glslang type to an SPV type, by calling into a
3057// recursive version of this function. This establishes the inherited
3058// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003059spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003060{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003061 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003062}
3063
3064// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003065// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003066// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003067spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003068 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3069 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003070{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003071 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003072
3073 switch (type.getBasicType()) {
3074 case glslang::EbtVoid:
3075 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003076 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003077 break;
3078 case glslang::EbtFloat:
3079 spvType = builder.makeFloatType(32);
3080 break;
3081 case glslang::EbtDouble:
3082 spvType = builder.makeFloatType(64);
3083 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003084 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003085 spvType = builder.makeFloatType(16);
3086 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003088 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3089 // a 32-bit int where non-0 means true.
3090 if (explicitLayout != glslang::ElpNone)
3091 spvType = builder.makeUintType(32);
3092 else
3093 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003094 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003095 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003096 spvType = builder.makeIntType(8);
3097 break;
3098 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003099 spvType = builder.makeUintType(8);
3100 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003101 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003102 spvType = builder.makeIntType(16);
3103 break;
3104 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003105 spvType = builder.makeUintType(16);
3106 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003107 case glslang::EbtInt:
3108 spvType = builder.makeIntType(32);
3109 break;
3110 case glslang::EbtUint:
3111 spvType = builder.makeUintType(32);
3112 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003113 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003114 spvType = builder.makeIntType(64);
3115 break;
3116 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003117 spvType = builder.makeUintType(64);
3118 break;
John Kessenich426394d2015-07-23 10:22:48 -06003119 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003120 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003121 spvType = builder.makeUintType(32);
3122 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003123#ifdef NV_EXTENSIONS
3124 case glslang::EbtAccStructNV:
3125 spvType = builder.makeAccelerationStructureNVType();
3126 break;
3127#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003128 case glslang::EbtSampler:
3129 {
3130 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003131 if (sampler.sampler) {
3132 // pure sampler
3133 spvType = builder.makeSamplerType();
3134 } else {
3135 // an image is present, make its type
3136 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3137 sampler.image ? 2 : 1, TranslateImageFormat(type));
3138 if (sampler.combined) {
3139 // already has both image and sampler, make the combined type
3140 spvType = builder.makeSampledImageType(spvType);
3141 }
John Kessenich55e7d112015-11-15 21:33:39 -07003142 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003143 }
John Kessenich140f3df2015-06-26 16:58:36 -06003144 break;
3145 case glslang::EbtStruct:
3146 case glslang::EbtBlock:
3147 {
3148 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003149 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003150
3151 // Try to share structs for different layouts, but not yet for other
3152 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003153 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003154 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003155 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157
3158 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003159 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003160 memberRemapper[glslangMembers].resize(glslangMembers->size());
3161 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003162 }
3163 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003164 case glslang::EbtReference:
3165 {
3166 // Make the forward pointer, then recurse to convert the structure type, then
3167 // patch up the forward pointer with a real pointer type.
3168 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3169 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3170 forwardPointers[type.getReferentType()] = forwardId;
3171 }
3172 spvType = forwardPointers[type.getReferentType()];
3173 if (!forwardReferenceOnly) {
3174 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3175 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3176 forwardPointers[type.getReferentType()],
3177 referentType);
3178 }
3179 }
3180 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003181 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003182 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184 }
3185
3186 if (type.isMatrix())
3187 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3188 else {
3189 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3190 if (type.getVectorSize() > 1)
3191 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3192 }
3193
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003194 if (type.isCoopMat()) {
3195 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3196 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3197 if (type.getBasicType() == glslang::EbtFloat16)
3198 builder.addCapability(spv::CapabilityFloat16);
3199
3200 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3201 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3202 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3203
3204 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3205 }
3206
John Kessenich140f3df2015-06-26 16:58:36 -06003207 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003208 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3209
John Kessenichc9a80832015-09-12 12:17:44 -06003210 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003211 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003212 // We need to decorate array strides for types needing explicit layout, except blocks.
3213 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003214 // Use a dummy glslang type for querying internal strides of
3215 // arrays of arrays, but using just a one-dimensional array.
3216 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003217 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3218 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003219
3220 // Will compute the higher-order strides here, rather than making a whole
3221 // pile of types and doing repetitive recursion on their contents.
3222 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3223 }
John Kessenichf8842e52016-01-04 19:22:56 -07003224
3225 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003226 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003227 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003228 if (stride > 0)
3229 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003230 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003231 }
3232 } else {
3233 // single-dimensional array, and don't yet have stride
3234
John Kessenichf8842e52016-01-04 19:22:56 -07003235 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003236 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3237 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003238 }
John Kessenich31ed4832015-09-09 17:51:38 -06003239
John Kessenichead86222018-03-28 18:01:20 -06003240 // Do the outer dimension, which might not be known for a runtime-sized array.
3241 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3242 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003243 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003244 else {
3245 if (!lastBufferBlockMember) {
3246 builder.addExtension("SPV_EXT_descriptor_indexing");
3247 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3248 }
John Kessenichead86222018-03-28 18:01:20 -06003249 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003250 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003251 if (stride > 0)
3252 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 }
3254
3255 return spvType;
3256}
3257
John Kessenich0e737842017-03-24 18:38:16 -06003258// TODO: this functionality should exist at a higher level, in creating the AST
3259//
3260// Identify interface members that don't have their required extension turned on.
3261//
3262bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3263{
Chao Chen3c366992018-09-19 11:41:59 -07003264#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003265 auto& extensions = glslangIntermediate->getRequestedExtensions();
3266
Rex Xubcf291a2017-03-29 23:01:36 +08003267 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3268 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3269 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003270 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3271 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3272 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003273
3274 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3275 if (member.getFieldName() == "gl_ViewportMask" &&
3276 extensions.find("GL_NV_viewport_array2") == extensions.end())
3277 return true;
3278 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3279 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3280 return true;
3281 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3282 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3283 return true;
3284 }
3285#endif
John Kessenich0e737842017-03-24 18:38:16 -06003286
3287 return false;
3288};
3289
John Kessenich6090df02016-06-30 21:18:02 -06003290// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3291// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3292// Mutually recursive with convertGlslangToSpvType().
3293spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3294 const glslang::TTypeList* glslangMembers,
3295 glslang::TLayoutPacking explicitLayout,
3296 const glslang::TQualifier& qualifier)
3297{
3298 // Create a vector of struct types for SPIR-V to consume
3299 std::vector<spv::Id> spvMembers;
3300 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 -06003301 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003302 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3303 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3304 if (glslangMember.hiddenMember()) {
3305 ++memberDelta;
3306 if (type.getBasicType() == glslang::EbtBlock)
3307 memberRemapper[glslangMembers][i] = -1;
3308 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003309 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003310 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003311 if (filterMember(glslangMember))
3312 continue;
3313 }
John Kessenich6090df02016-06-30 21:18:02 -06003314 // modify just this child's view of the qualifier
3315 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3316 InheritQualifiers(memberQualifier, qualifier);
3317
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003318 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003319 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003320 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003321
3322 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003323 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3324 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003325
3326 // Make forward pointers for any pointer members, and create a list of members to
3327 // convert to spirv types after creating the struct.
3328 if (glslangMember.getBasicType() == glslang::EbtReference) {
3329 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3330 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3331 }
3332 spvMembers.push_back(
3333 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3334 } else {
3335 spvMembers.push_back(
3336 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3337 }
John Kessenich6090df02016-06-30 21:18:02 -06003338 }
3339 }
3340
3341 // Make the SPIR-V type
3342 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003343 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003344 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3345
3346 // Decorate it
3347 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3348
John Kessenichd72f4882019-01-16 14:55:37 +07003349 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003350 auto it = deferredForwardPointers[i];
3351 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3352 }
3353
John Kessenich6090df02016-06-30 21:18:02 -06003354 return spvType;
3355}
3356
3357void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3358 const glslang::TTypeList* glslangMembers,
3359 glslang::TLayoutPacking explicitLayout,
3360 const glslang::TQualifier& qualifier,
3361 spv::Id spvType)
3362{
3363 // Name and decorate the non-hidden members
3364 int offset = -1;
3365 int locationOffset = 0; // for use within the members of this struct
3366 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3367 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3368 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003369 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003370 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003371 if (filterMember(glslangMember))
3372 continue;
3373 }
John Kessenich6090df02016-06-30 21:18:02 -06003374
3375 // modify just this child's view of the qualifier
3376 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3377 InheritQualifiers(memberQualifier, qualifier);
3378
3379 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003380 if (member < 0)
3381 continue;
3382
3383 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3384 builder.addMemberDecoration(spvType, member,
3385 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3386 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3387 // Add interpolation and auxiliary storage decorations only to
3388 // top-level members of Input and Output storage classes
3389 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3390 type.getQualifier().storage == glslang::EvqVaryingOut) {
3391 if (type.getBasicType() == glslang::EbtBlock ||
3392 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3393 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3394 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003395#ifdef NV_EXTENSIONS
3396 addMeshNVDecoration(spvType, member, memberQualifier);
3397#endif
John Kessenich6090df02016-06-30 21:18:02 -06003398 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003399 }
3400 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003401
John Kessenich5d610ee2018-03-07 18:05:55 -07003402 if (type.getBasicType() == glslang::EbtBlock &&
3403 qualifier.storage == glslang::EvqBuffer) {
3404 // Add memory decorations only to top-level members of shader storage block
3405 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003406 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003407 for (unsigned int i = 0; i < memory.size(); ++i)
3408 builder.addMemberDecoration(spvType, member, memory[i]);
3409 }
John Kessenich6090df02016-06-30 21:18:02 -06003410
John Kessenich5d610ee2018-03-07 18:05:55 -07003411 // Location assignment was already completed correctly by the front end,
3412 // just track whether a member needs to be decorated.
3413 // Ignore member locations if the container is an array, as that's
3414 // ill-specified and decisions have been made to not allow this.
3415 if (! type.isArray() && memberQualifier.hasLocation())
3416 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003417
John Kessenich5d610ee2018-03-07 18:05:55 -07003418 if (qualifier.hasLocation()) // track for upcoming inheritance
3419 locationOffset += glslangIntermediate->computeTypeLocationSize(
3420 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003421
John Kessenich5d610ee2018-03-07 18:05:55 -07003422 // component, XFB, others
3423 if (glslangMember.getQualifier().hasComponent())
3424 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3425 glslangMember.getQualifier().layoutComponent);
3426 if (glslangMember.getQualifier().hasXfbOffset())
3427 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3428 glslangMember.getQualifier().layoutXfbOffset);
3429 else if (explicitLayout != glslang::ElpNone) {
3430 // figure out what to do with offset, which is accumulating
3431 int nextOffset;
3432 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3433 if (offset >= 0)
3434 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3435 offset = nextOffset;
3436 }
John Kessenich6090df02016-06-30 21:18:02 -06003437
John Kessenich5d610ee2018-03-07 18:05:55 -07003438 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3439 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3440 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003441
John Kessenich5d610ee2018-03-07 18:05:55 -07003442 // built-in variable decorations
3443 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3444 if (builtIn != spv::BuiltInMax)
3445 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003446
John Kessenich5611c6d2018-04-05 11:25:02 -06003447 // nonuniform
3448 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3449
John Kessenichead86222018-03-28 18:01:20 -06003450 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3451 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3452 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3453 memberQualifier.semanticName);
3454 }
3455
chaoc771d89f2017-01-13 01:10:53 -08003456#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003457 if (builtIn == spv::BuiltInLayer) {
3458 // SPV_NV_viewport_array2 extension
3459 if (glslangMember.getQualifier().layoutViewportRelative){
3460 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3461 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3462 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003463 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003464 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3465 builder.addMemberDecoration(spvType, member,
3466 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3467 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3468 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3469 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003470 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003471 }
3472 if (glslangMember.getQualifier().layoutPassthrough) {
3473 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3474 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3475 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3476 }
chaoc771d89f2017-01-13 01:10:53 -08003477#endif
John Kessenich6090df02016-06-30 21:18:02 -06003478 }
3479
3480 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003481 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3482 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003483}
3484
John Kessenich6c292d32016-02-15 20:58:50 -07003485// Turn the expression forming the array size into an id.
3486// This is not quite trivial, because of specialization constants.
3487// Sometimes, a raw constant is turned into an Id, and sometimes
3488// a specialization constant expression is.
3489spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3490{
3491 // First, see if this is sized with a node, meaning a specialization constant:
3492 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3493 if (specNode != nullptr) {
3494 builder.clearAccessChain();
3495 specNode->traverse(this);
3496 return accessChainLoad(specNode->getAsTyped()->getType());
3497 }
qining25262b32016-05-06 17:25:16 -04003498
John Kessenich6c292d32016-02-15 20:58:50 -07003499 // Otherwise, need a compile-time (front end) size, get it:
3500 int size = arraySizes.getDimSize(dim);
3501 assert(size > 0);
3502 return builder.makeUintConstant(size);
3503}
3504
John Kessenich103bef92016-02-08 21:38:15 -07003505// Wrap the builder's accessChainLoad to:
3506// - localize handling of RelaxedPrecision
3507// - use the SPIR-V inferred type instead of another conversion of the glslang type
3508// (avoids unnecessary work and possible type punning for structures)
3509// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003510spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3511{
John Kessenich103bef92016-02-08 21:38:15 -07003512 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003513
3514 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3515 coherentFlags |= TranslateCoherent(type);
3516
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003517 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003518 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003519
John Kessenich5611c6d2018-04-05 11:25:02 -06003520 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003521 TranslateNonUniformDecoration(type.getQualifier()),
3522 nominalTypeId,
3523 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003524 TranslateMemoryScope(coherentFlags),
3525 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003526
3527 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003528 if (type.getBasicType() == glslang::EbtBool) {
3529 if (builder.isScalarType(nominalTypeId)) {
3530 // Conversion for bool
3531 spv::Id boolType = builder.makeBoolType();
3532 if (nominalTypeId != boolType)
3533 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3534 } else if (builder.isVectorType(nominalTypeId)) {
3535 // Conversion for bvec
3536 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3537 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3538 if (nominalTypeId != bvecType)
3539 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3540 }
3541 }
John Kessenich103bef92016-02-08 21:38:15 -07003542
3543 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003544}
3545
Rex Xu27253232016-02-23 17:51:09 +08003546// Wrap the builder's accessChainStore to:
3547// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003548//
3549// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003550void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3551{
3552 // Need to convert to abstract types when necessary
3553 if (type.getBasicType() == glslang::EbtBool) {
3554 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3555
3556 if (builder.isScalarType(nominalTypeId)) {
3557 // Conversion for bool
3558 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003559 if (nominalTypeId != boolType) {
3560 // keep these outside arguments, for determinant order-of-evaluation
3561 spv::Id one = builder.makeUintConstant(1);
3562 spv::Id zero = builder.makeUintConstant(0);
3563 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3564 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003565 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003566 } else if (builder.isVectorType(nominalTypeId)) {
3567 // Conversion for bvec
3568 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3569 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003570 if (nominalTypeId != bvecType) {
3571 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003572 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3573 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3574 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003575 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003576 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3577 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003578 }
3579 }
3580
Jeff Bolz36831c92018-09-05 10:11:41 -05003581 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3582 coherentFlags |= TranslateCoherent(type);
3583
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003584 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003585 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003586
Jeff Bolz36831c92018-09-05 10:11:41 -05003587 builder.accessChainStore(rvalue,
3588 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003589 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003590}
3591
John Kessenich4bf71552016-09-02 11:20:21 -06003592// For storing when types match at the glslang level, but not might match at the
3593// SPIR-V level.
3594//
3595// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003596// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003597// as in a member-decorated way.
3598//
3599// NOTE: This function can handle any store request; if it's not special it
3600// simplifies to a simple OpStore.
3601//
3602// Implicitly uses the existing builder.accessChain as the storage target.
3603void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3604{
John Kessenichb3e24e42016-09-11 12:33:43 -06003605 // we only do the complex path here if it's an aggregate
3606 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003607 accessChainStore(type, rValue);
3608 return;
3609 }
3610
John Kessenichb3e24e42016-09-11 12:33:43 -06003611 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003612 spv::Id rType = builder.getTypeId(rValue);
3613 spv::Id lValue = builder.accessChainGetLValue();
3614 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3615 if (lType == rType) {
3616 accessChainStore(type, rValue);
3617 return;
3618 }
3619
John Kessenichb3e24e42016-09-11 12:33:43 -06003620 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003621 // where the two types were the same type in GLSL. This requires member
3622 // by member copy, recursively.
3623
John Kessenichb3e24e42016-09-11 12:33:43 -06003624 // If an array, copy element by element.
3625 if (type.isArray()) {
3626 glslang::TType glslangElementType(type, 0);
3627 spv::Id elementRType = builder.getContainedTypeId(rType);
3628 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3629 // get the source member
3630 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003631
John Kessenichb3e24e42016-09-11 12:33:43 -06003632 // set up the target storage
3633 builder.clearAccessChain();
3634 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003635 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003636
John Kessenichb3e24e42016-09-11 12:33:43 -06003637 // store the member
3638 multiTypeStore(glslangElementType, elementRValue);
3639 }
3640 } else {
3641 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003642
John Kessenichb3e24e42016-09-11 12:33:43 -06003643 // loop over structure members
3644 const glslang::TTypeList& members = *type.getStruct();
3645 for (int m = 0; m < (int)members.size(); ++m) {
3646 const glslang::TType& glslangMemberType = *members[m].type;
3647
3648 // get the source member
3649 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3650 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3651
3652 // set up the target storage
3653 builder.clearAccessChain();
3654 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003655 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003656
3657 // store the member
3658 multiTypeStore(glslangMemberType, memberRValue);
3659 }
John Kessenich4bf71552016-09-02 11:20:21 -06003660 }
3661}
3662
John Kessenichf85e8062015-12-19 13:57:10 -07003663// Decide whether or not this type should be
3664// decorated with offsets and strides, and if so
3665// whether std140 or std430 rules should be applied.
3666glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003667{
John Kessenichf85e8062015-12-19 13:57:10 -07003668 // has to be a block
3669 if (type.getBasicType() != glslang::EbtBlock)
3670 return glslang::ElpNone;
3671
Chao Chen3c366992018-09-19 11:41:59 -07003672 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003673 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003674 type.getQualifier().storage != glslang::EvqBuffer &&
3675 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003676 return glslang::ElpNone;
3677
3678 // return the layout to use
3679 switch (type.getQualifier().layoutPacking) {
3680 case glslang::ElpStd140:
3681 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003682 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003683 return type.getQualifier().layoutPacking;
3684 default:
3685 return glslang::ElpNone;
3686 }
John Kessenich31ed4832015-09-09 17:51:38 -06003687}
3688
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003689// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003690int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003691{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003692 int size;
John Kessenich49987892015-12-29 17:11:44 -07003693 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003694 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003695
3696 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003697}
3698
John Kessenich49987892015-12-29 17:11:44 -07003699// 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 -07003700// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003701int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003702{
John Kessenich49987892015-12-29 17:11:44 -07003703 glslang::TType elementType;
3704 elementType.shallowCopy(matrixType);
3705 elementType.clearArraySizes();
3706
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003707 int size;
John Kessenich49987892015-12-29 17:11:44 -07003708 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003709 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003710
3711 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003712}
3713
John Kessenich5e4b1242015-08-06 22:53:06 -06003714// Given a member type of a struct, realign the current offset for it, and compute
3715// the next (not yet aligned) offset for the next member, which will get aligned
3716// on the next call.
3717// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3718// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3719// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003720void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003721 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003722{
3723 // this will get a positive value when deemed necessary
3724 nextOffset = -1;
3725
John Kessenich5e4b1242015-08-06 22:53:06 -06003726 // override anything in currentOffset with user-set offset
3727 if (memberType.getQualifier().hasOffset())
3728 currentOffset = memberType.getQualifier().layoutOffset;
3729
3730 // It could be that current linker usage in glslang updated all the layoutOffset,
3731 // in which case the following code does not matter. But, that's not quite right
3732 // once cross-compilation unit GLSL validation is done, as the original user
3733 // settings are needed in layoutOffset, and then the following will come into play.
3734
John Kessenichf85e8062015-12-19 13:57:10 -07003735 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003736 if (! memberType.getQualifier().hasOffset())
3737 currentOffset = -1;
3738
3739 return;
3740 }
3741
John Kessenichf85e8062015-12-19 13:57:10 -07003742 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 if (currentOffset < 0)
3744 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003745
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3747 // but possibly not yet correctly aligned.
3748
3749 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003750 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003751 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003752
3753 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003754 // TODO: make this consistent in early phases of code:
3755 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3756 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3757 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003758 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003759 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003760 int dummySize;
3761 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3762 if (componentAlignment <= 4)
3763 memberAlignment = componentAlignment;
3764 }
3765
3766 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003768
3769 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003770 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003771 glslang::RoundToPow2(currentOffset, 16);
3772
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 nextOffset = currentOffset + memberSize;
3774}
3775
David Netoa901ffe2016-06-08 14:11:40 +01003776void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003777{
David Netoa901ffe2016-06-08 14:11:40 +01003778 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3779 switch (glslangBuiltIn)
3780 {
3781 case glslang::EbvClipDistance:
3782 case glslang::EbvCullDistance:
3783 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003784#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003785 case glslang::EbvViewportMaskNV:
3786 case glslang::EbvSecondaryPositionNV:
3787 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003788 case glslang::EbvPositionPerViewNV:
3789 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003790 case glslang::EbvTaskCountNV:
3791 case glslang::EbvPrimitiveCountNV:
3792 case glslang::EbvPrimitiveIndicesNV:
3793 case glslang::EbvClipDistancePerViewNV:
3794 case glslang::EbvCullDistancePerViewNV:
3795 case glslang::EbvLayerPerViewNV:
3796 case glslang::EbvMeshViewCountNV:
3797 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003798#endif
David Netoa901ffe2016-06-08 14:11:40 +01003799 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3800 // Alternately, we could just call this for any glslang built-in, since the
3801 // capability already guards against duplicates.
3802 TranslateBuiltInDecoration(glslangBuiltIn, false);
3803 break;
3804 default:
3805 // Capabilities were already generated when the struct was declared.
3806 break;
3807 }
John Kessenichebb50532016-05-16 19:22:05 -06003808}
3809
John Kessenich6fccb3c2016-09-19 16:01:41 -06003810bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003811{
John Kessenicheee9d532016-09-19 18:09:30 -06003812 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003813}
3814
John Kessenichd41993d2017-09-10 15:21:05 -06003815// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003816// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3817// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003818bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003819{
John Kessenich6a14f782017-12-04 02:48:10 -07003820 assert(qualifier == glslang::EvqIn ||
3821 qualifier == glslang::EvqOut ||
3822 qualifier == glslang::EvqInOut ||
3823 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003824 return qualifier != glslang::EvqConstReadOnly;
3825}
3826
3827// Is parameter pass-by-original?
3828bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3829 bool implicitThisParam)
3830{
3831 if (implicitThisParam) // implicit this
3832 return true;
3833 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003834 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003835 return paramType.containsOpaque() || // sampler, etc.
3836 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3837}
3838
John Kessenich140f3df2015-06-26 16:58:36 -06003839// Make all the functions, skeletally, without actually visiting their bodies.
3840void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3841{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003842 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003843 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3844 if (paramPrecision != spv::NoPrecision)
3845 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003846 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003847 if (type.getBasicType() == glslang::EbtReference) {
3848 // Original and non-writable params pass the pointer directly and
3849 // use restrict/aliased, others are stored to a pointer in Function
3850 // memory and use RestrictPointer/AliasedPointer.
3851 if (originalParam(type.getQualifier().storage, type, false) ||
3852 !writableParam(type.getQualifier().storage)) {
3853 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3854 } else {
3855 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3856 }
3857 }
John Kessenichfad62972017-07-18 02:35:46 -06003858 };
3859
John Kessenich140f3df2015-06-26 16:58:36 -06003860 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3861 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003862 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003863 continue;
3864
3865 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003866 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003867 //
qining25262b32016-05-06 17:25:16 -04003868 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003869 // function. What it is an address of varies:
3870 //
John Kessenich4bf71552016-09-02 11:20:21 -06003871 // - "in" parameters not marked as "const" can be written to without modifying the calling
3872 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003873 //
3874 // - "const in" parameters can just be the r-value, as no writes need occur.
3875 //
John Kessenich4bf71552016-09-02 11:20:21 -06003876 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3877 // 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 -06003878
3879 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003880 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003881 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3882
John Kessenichfad62972017-07-18 02:35:46 -06003883 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3884 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003885
John Kessenichfad62972017-07-18 02:35:46 -06003886 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003887 for (int p = 0; p < (int)parameters.size(); ++p) {
3888 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3889 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003890 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003891 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003892 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003893 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3894 else
John Kessenich4bf71552016-09-02 11:20:21 -06003895 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003896 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003897 paramTypes.push_back(typeId);
3898 }
3899
3900 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003901 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3902 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003903 glslFunction->getName().c_str(), paramTypes,
3904 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003905 if (implicitThis)
3906 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003907
3908 // Track function to emit/call later
3909 functionMap[glslFunction->getName().c_str()] = function;
3910
3911 // Set the parameter id's
3912 for (int p = 0; p < (int)parameters.size(); ++p) {
3913 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3914 // give a name too
3915 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3916 }
3917 }
3918}
3919
3920// Process all the initializers, while skipping the functions and link objects
3921void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3922{
3923 builder.setBuildPoint(shaderEntry->getLastBlock());
3924 for (int i = 0; i < (int)initializers.size(); ++i) {
3925 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3926 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3927
3928 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003929 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003930 initializer->traverse(this);
3931 }
3932 }
3933}
3934
3935// Process all the functions, while skipping initializers.
3936void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3937{
3938 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3939 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003940 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003941 node->traverse(this);
3942 }
3943}
3944
3945void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3946{
qining25262b32016-05-06 17:25:16 -04003947 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003948 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003949 currentFunction = functionMap[node->getName().c_str()];
3950 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003951 builder.setBuildPoint(functionBlock);
3952}
3953
Rex Xu04db3f52015-09-16 11:44:02 +08003954void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003955{
Rex Xufc618912015-09-09 16:42:49 +08003956 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003957
3958 glslang::TSampler sampler = {};
3959 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003960#ifdef AMD_EXTENSIONS
3961 bool f16ShadowCompare = false;
3962#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003963 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003964 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3965 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003966#ifdef AMD_EXTENSIONS
3967 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3968#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003969 }
3970
John Kessenich140f3df2015-06-26 16:58:36 -06003971 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3972 builder.clearAccessChain();
3973 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003974
3975 // Special case l-value operands
3976 bool lvalue = false;
3977 switch (node.getOp()) {
3978 case glslang::EOpImageAtomicAdd:
3979 case glslang::EOpImageAtomicMin:
3980 case glslang::EOpImageAtomicMax:
3981 case glslang::EOpImageAtomicAnd:
3982 case glslang::EOpImageAtomicOr:
3983 case glslang::EOpImageAtomicXor:
3984 case glslang::EOpImageAtomicExchange:
3985 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003986 case glslang::EOpImageAtomicLoad:
3987 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003988 if (i == 0)
3989 lvalue = true;
3990 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003991 case glslang::EOpSparseImageLoad:
3992 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3993 lvalue = true;
3994 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003995#ifdef AMD_EXTENSIONS
3996 case glslang::EOpSparseTexture:
3997 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3998 lvalue = true;
3999 break;
4000 case glslang::EOpSparseTextureClamp:
4001 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4002 lvalue = true;
4003 break;
4004 case glslang::EOpSparseTextureLod:
4005 case glslang::EOpSparseTextureOffset:
4006 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4007 lvalue = true;
4008 break;
4009#else
Rex Xu48edadf2015-12-31 16:11:41 +08004010 case glslang::EOpSparseTexture:
4011 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4012 lvalue = true;
4013 break;
4014 case glslang::EOpSparseTextureClamp:
4015 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4016 lvalue = true;
4017 break;
4018 case glslang::EOpSparseTextureLod:
4019 case glslang::EOpSparseTextureOffset:
4020 if (i == 3)
4021 lvalue = true;
4022 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004023#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004024 case glslang::EOpSparseTextureFetch:
4025 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4026 lvalue = true;
4027 break;
4028 case glslang::EOpSparseTextureFetchOffset:
4029 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4030 lvalue = true;
4031 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004032#ifdef AMD_EXTENSIONS
4033 case glslang::EOpSparseTextureLodOffset:
4034 case glslang::EOpSparseTextureGrad:
4035 case glslang::EOpSparseTextureOffsetClamp:
4036 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4037 lvalue = true;
4038 break;
4039 case glslang::EOpSparseTextureGradOffset:
4040 case glslang::EOpSparseTextureGradClamp:
4041 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4042 lvalue = true;
4043 break;
4044 case glslang::EOpSparseTextureGradOffsetClamp:
4045 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4046 lvalue = true;
4047 break;
4048#else
Rex Xu48edadf2015-12-31 16:11:41 +08004049 case glslang::EOpSparseTextureLodOffset:
4050 case glslang::EOpSparseTextureGrad:
4051 case glslang::EOpSparseTextureOffsetClamp:
4052 if (i == 4)
4053 lvalue = true;
4054 break;
4055 case glslang::EOpSparseTextureGradOffset:
4056 case glslang::EOpSparseTextureGradClamp:
4057 if (i == 5)
4058 lvalue = true;
4059 break;
4060 case glslang::EOpSparseTextureGradOffsetClamp:
4061 if (i == 6)
4062 lvalue = true;
4063 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004064#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004065 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004066 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4067 lvalue = true;
4068 break;
4069 case glslang::EOpSparseTextureGatherOffset:
4070 case glslang::EOpSparseTextureGatherOffsets:
4071 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4072 lvalue = true;
4073 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004074#ifdef AMD_EXTENSIONS
4075 case glslang::EOpSparseTextureGatherLod:
4076 if (i == 3)
4077 lvalue = true;
4078 break;
4079 case glslang::EOpSparseTextureGatherLodOffset:
4080 case glslang::EOpSparseTextureGatherLodOffsets:
4081 if (i == 4)
4082 lvalue = true;
4083 break;
Rex Xu129799a2017-07-05 17:23:28 +08004084 case glslang::EOpSparseImageLoadLod:
4085 if (i == 3)
4086 lvalue = true;
4087 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004088#endif
Chao Chen3a137962018-09-19 11:41:27 -07004089#ifdef NV_EXTENSIONS
4090 case glslang::EOpImageSampleFootprintNV:
4091 if (i == 4)
4092 lvalue = true;
4093 break;
4094 case glslang::EOpImageSampleFootprintClampNV:
4095 case glslang::EOpImageSampleFootprintLodNV:
4096 if (i == 5)
4097 lvalue = true;
4098 break;
4099 case glslang::EOpImageSampleFootprintGradNV:
4100 if (i == 6)
4101 lvalue = true;
4102 break;
4103 case glslang::EOpImageSampleFootprintGradClampNV:
4104 if (i == 7)
4105 lvalue = true;
4106 break;
4107#endif
Rex Xufc618912015-09-09 16:42:49 +08004108 default:
4109 break;
4110 }
4111
Rex Xu6b86d492015-09-16 17:48:22 +08004112 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004113 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004114 else
John Kessenich32cfd492016-02-02 12:37:46 -07004115 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004116 }
4117}
4118
John Kessenichfc51d282015-08-19 13:34:18 -06004119void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004120{
John Kessenichfc51d282015-08-19 13:34:18 -06004121 builder.clearAccessChain();
4122 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004123 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004124}
John Kessenich140f3df2015-06-26 16:58:36 -06004125
John Kessenichfc51d282015-08-19 13:34:18 -06004126spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4127{
John Kesseniche485c7a2017-05-31 18:50:53 -06004128 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004129 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004130
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004131 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004132
John Kessenichfc51d282015-08-19 13:34:18 -06004133 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004134
4135 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4136 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4137 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004138#ifdef AMD_EXTENSIONS
4139 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4140 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4141 : false;
4142#endif
4143
John Kessenichfc51d282015-08-19 13:34:18 -06004144 std::vector<spv::Id> arguments;
4145 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004146 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004147 else
4148 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004149 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004150
4151 spv::Builder::TextureParameters params = { };
4152 params.sampler = arguments[0];
4153
Rex Xu04db3f52015-09-16 11:44:02 +08004154 glslang::TCrackedTextureOp cracked;
4155 node->crackTexture(sampler, cracked);
4156
amhagan05506bb2017-06-13 16:53:02 -04004157 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004158
John Kessenichfc51d282015-08-19 13:34:18 -06004159 // Check for queries
4160 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004161 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4162 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004163 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004164
John Kessenichfc51d282015-08-19 13:34:18 -06004165 switch (node->getOp()) {
4166 case glslang::EOpImageQuerySize:
4167 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004168 if (arguments.size() > 1) {
4169 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004170 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004171 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004172 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004173 case glslang::EOpImageQuerySamples:
4174 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004175 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004176 case glslang::EOpTextureQueryLod:
4177 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004178 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004179 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004180 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004181 case glslang::EOpSparseTexelsResident:
4182 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004183 default:
4184 assert(0);
4185 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 }
John Kessenich140f3df2015-06-26 16:58:36 -06004187 }
4188
LoopDawg4425f242018-02-18 11:40:01 -07004189 int components = node->getType().getVectorSize();
4190
4191 if (node->getOp() == glslang::EOpTextureFetch) {
4192 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4193 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4194 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4195 // here around e.g. which ones return scalars or other types.
4196 components = 4;
4197 }
4198
4199 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4200
4201 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4202
Rex Xufc618912015-09-09 16:42:49 +08004203 // Check for image functions other than queries
4204 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004205 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004206 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004207 spv::IdImmediate image = { true, *(opIt++) };
4208 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004209
4210 // Handle subpass operations
4211 // TODO: GLSL should change to have the "MS" only on the type rather than the
4212 // built-in function.
4213 if (cracked.subpass) {
4214 // add on the (0,0) coordinate
4215 spv::Id zero = builder.makeIntConstant(0);
4216 std::vector<spv::Id> comps;
4217 comps.push_back(zero);
4218 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004219 spv::IdImmediate coord = { true,
4220 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4221 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004222 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004223 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4224 operands.push_back(imageOperands);
4225 spv::IdImmediate imageOperand = { true, *(opIt++) };
4226 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004227 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004228 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4229 builder.setPrecision(result, precision);
4230 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004231 }
4232
John Kessenich149afc32018-08-14 13:31:43 -06004233 spv::IdImmediate coord = { true, *(opIt++) };
4234 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004235#ifdef AMD_EXTENSIONS
4236 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4237#else
John Kessenich56bab042015-09-16 10:54:31 -06004238 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004239#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004240 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004241 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004242 mask = mask | spv::ImageOperandsSampleMask;
4243 }
Rex Xu129799a2017-07-05 17:23:28 +08004244#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004245 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004246 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4247 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004248 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004249 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004250#endif
4251 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4252 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4253 if (mask) {
4254 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4255 operands.push_back(imageOperands);
4256 }
4257 if (mask & spv::ImageOperandsSampleMask) {
4258 spv::IdImmediate imageOperand = { true, *opIt++ };
4259 operands.push_back(imageOperand);
4260 }
4261#ifdef AMD_EXTENSIONS
4262 if (mask & spv::ImageOperandsLodMask) {
4263 spv::IdImmediate imageOperand = { true, *opIt++ };
4264 operands.push_back(imageOperand);
4265 }
4266#endif
4267 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4268 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4269 operands.push_back(imageOperand);
4270 }
4271
John Kessenich149afc32018-08-14 13:31:43 -06004272 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004273 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004274
John Kessenich149afc32018-08-14 13:31:43 -06004275 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004276 builder.setPrecision(result[0], precision);
4277
4278 // If needed, add a conversion constructor to the proper size.
4279 if (components != node->getType().getVectorSize())
4280 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4281
4282 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004283#ifdef AMD_EXTENSIONS
4284 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4285#else
John Kessenich56bab042015-09-16 10:54:31 -06004286 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004287#endif
Rex Xu129799a2017-07-05 17:23:28 +08004288
Jeff Bolz36831c92018-09-05 10:11:41 -05004289 // Push the texel value before the operands
4290#ifdef AMD_EXTENSIONS
4291 if (sampler.ms || cracked.lod) {
4292#else
4293 if (sampler.ms) {
4294#endif
John Kessenich149afc32018-08-14 13:31:43 -06004295 spv::IdImmediate texel = { true, *(opIt + 1) };
4296 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004297 } else {
4298 spv::IdImmediate texel = { true, *opIt };
4299 operands.push_back(texel);
4300 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004301
4302 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4303 if (sampler.ms) {
4304 mask = mask | spv::ImageOperandsSampleMask;
4305 }
4306#ifdef AMD_EXTENSIONS
4307 if (cracked.lod) {
4308 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4309 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4310 mask = mask | spv::ImageOperandsLodMask;
4311 }
4312#endif
4313 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4314 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4315 if (mask) {
4316 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4317 operands.push_back(imageOperands);
4318 }
4319 if (mask & spv::ImageOperandsSampleMask) {
4320 spv::IdImmediate imageOperand = { true, *opIt++ };
4321 operands.push_back(imageOperand);
4322 }
4323#ifdef AMD_EXTENSIONS
4324 if (mask & spv::ImageOperandsLodMask) {
4325 spv::IdImmediate imageOperand = { true, *opIt++ };
4326 operands.push_back(imageOperand);
4327 }
4328#endif
4329 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4330 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4331 operands.push_back(imageOperand);
4332 }
4333
John Kessenich56bab042015-09-16 10:54:31 -06004334 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004335 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004336 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004337 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004338#ifdef AMD_EXTENSIONS
4339 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4340#else
Rex Xu5eafa472016-02-19 22:24:03 +08004341 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004342#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004343 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004344 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004345 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4346
Jeff Bolz36831c92018-09-05 10:11:41 -05004347 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004348 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004349 mask = mask | spv::ImageOperandsSampleMask;
4350 }
Rex Xu129799a2017-07-05 17:23:28 +08004351#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004352 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004353 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4354 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4355
Jeff Bolz36831c92018-09-05 10:11:41 -05004356 mask = mask | spv::ImageOperandsLodMask;
4357 }
4358#endif
4359 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4360 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4361 if (mask) {
4362 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004363 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004364 }
4365 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004366 spv::IdImmediate imageOperand = { true, *opIt++ };
4367 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004368 }
4369#ifdef AMD_EXTENSIONS
4370 if (mask & spv::ImageOperandsLodMask) {
4371 spv::IdImmediate imageOperand = { true, *opIt++ };
4372 operands.push_back(imageOperand);
4373 }
Rex Xu129799a2017-07-05 17:23:28 +08004374#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004375 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4376 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4377 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004378 }
4379
4380 // Create the return type that was a special structure
4381 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004382 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004383 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4384 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4385
4386 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4387
4388 // Decode the return type
4389 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4390 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004391 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004392 // Process image atomic operations
4393
4394 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4395 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004396 // For non-MS, the sample value should be 0
4397 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4398 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004399
Jeff Bolz36831c92018-09-05 10:11:41 -05004400 spv::Id resultTypeId;
4401 // imageAtomicStore has a void return type so base the pointer type on
4402 // the type of the value operand.
4403 if (node->getOp() == glslang::EOpImageAtomicStore) {
4404 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4405 } else {
4406 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4407 }
John Kessenich56bab042015-09-16 10:54:31 -06004408 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004409
4410 std::vector<spv::Id> operands;
4411 operands.push_back(pointer);
4412 for (; opIt != arguments.end(); ++opIt)
4413 operands.push_back(*opIt);
4414
John Kessenich8c8505c2016-07-26 12:50:38 -06004415 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004416 }
4417 }
4418
amhagan05506bb2017-06-13 16:53:02 -04004419#ifdef AMD_EXTENSIONS
4420 // Check for fragment mask functions other than queries
4421 if (cracked.fragMask) {
4422 assert(sampler.ms);
4423
4424 auto opIt = arguments.begin();
4425 std::vector<spv::Id> operands;
4426
4427 // Extract the image if necessary
4428 if (builder.isSampledImage(params.sampler))
4429 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4430
4431 operands.push_back(params.sampler);
4432 ++opIt;
4433
4434 if (sampler.isSubpass()) {
4435 // add on the (0,0) coordinate
4436 spv::Id zero = builder.makeIntConstant(0);
4437 std::vector<spv::Id> comps;
4438 comps.push_back(zero);
4439 comps.push_back(zero);
4440 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4441 }
4442
4443 for (; opIt != arguments.end(); ++opIt)
4444 operands.push_back(*opIt);
4445
4446 spv::Op fragMaskOp = spv::OpNop;
4447 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4448 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4449 else if (node->getOp() == glslang::EOpFragmentFetch)
4450 fragMaskOp = spv::OpFragmentFetchAMD;
4451
4452 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4453 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4454 return builder.createOp(fragMaskOp, resultType(), operands);
4455 }
4456#endif
4457
Rex Xufc618912015-09-09 16:42:49 +08004458 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004459 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004460#ifdef NV_EXTENSIONS
4461 bool imageFootprint = node->isImageFootprint();
4462#endif
4463
Rex Xu71519fe2015-11-11 15:35:47 +08004464 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4465
John Kessenichfc51d282015-08-19 13:34:18 -06004466 // check for bias argument
4467 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004468#ifdef AMD_EXTENSIONS
4469 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4470#else
Rex Xu71519fe2015-11-11 15:35:47 +08004471 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004472#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004473 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004474#ifdef AMD_EXTENSIONS
4475 if (cracked.gather)
4476 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004477
4478 if (f16ShadowCompare)
4479 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004480#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004481 if (cracked.offset)
4482 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004483#ifdef AMD_EXTENSIONS
4484 else if (cracked.offsets)
4485 ++nonBiasArgCount;
4486#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004487 if (cracked.grad)
4488 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004489 if (cracked.lodClamp)
4490 ++nonBiasArgCount;
4491 if (sparse)
4492 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004493#ifdef NV_EXTENSIONS
4494 if (imageFootprint)
4495 //Following three extra arguments
4496 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4497 nonBiasArgCount += 3;
4498#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004499 if ((int)arguments.size() > nonBiasArgCount)
4500 bias = true;
4501 }
4502
John Kessenicha5c33d62016-06-02 23:45:21 -06004503 // See if the sampler param should really be just the SPV image part
4504 if (cracked.fetch) {
4505 // a fetch needs to have the image extracted first
4506 if (builder.isSampledImage(params.sampler))
4507 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4508 }
4509
Rex Xu225e0fc2016-11-17 17:47:59 +08004510#ifdef AMD_EXTENSIONS
4511 if (cracked.gather) {
4512 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4513 if (bias || cracked.lod ||
4514 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4515 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004516 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004517 }
4518 }
4519#endif
4520
John Kessenichfc51d282015-08-19 13:34:18 -06004521 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004522
John Kessenichfc51d282015-08-19 13:34:18 -06004523 params.coords = arguments[1];
4524 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004525 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004526
4527 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004528#ifdef AMD_EXTENSIONS
4529 if (cubeCompare || f16ShadowCompare) {
4530#else
Rex Xu48edadf2015-12-31 16:11:41 +08004531 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004532#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004533 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004534 ++extraArgs;
4535 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004536 params.Dref = arguments[2];
4537 ++extraArgs;
4538 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004539 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004540 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004541 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004542 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004543 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004544 dRefComp = builder.getNumComponents(params.coords) - 1;
4545 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004546 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4547 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004548
4549 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004550 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004551 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004552 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004553 } else if (glslangIntermediate->getStage() != EShLangFragment
4554#ifdef NV_EXTENSIONS
4555 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4556 && !(glslangIntermediate->getStage() == EShLangCompute &&
4557 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4558#endif
4559 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004560 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4561 noImplicitLod = true;
4562 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004563
4564 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004565 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004566 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004567 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004568 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004569
4570 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004571 if (cracked.grad) {
4572 params.gradX = arguments[2 + extraArgs];
4573 params.gradY = arguments[3 + extraArgs];
4574 extraArgs += 2;
4575 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004576
4577 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004578 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004579 params.offset = arguments[2 + extraArgs];
4580 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004581 } else if (cracked.offsets) {
4582 params.offsets = arguments[2 + extraArgs];
4583 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004584 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004585
4586 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004587 if (cracked.lodClamp) {
4588 params.lodClamp = arguments[2 + extraArgs];
4589 ++extraArgs;
4590 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004591 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004592 if (sparse) {
4593 params.texelOut = arguments[2 + extraArgs];
4594 ++extraArgs;
4595 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004596
John Kessenich76d4dfc2016-06-16 12:43:23 -06004597 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004598 if (cracked.gather && ! sampler.shadow) {
4599 // default component is 0, if missing, otherwise an argument
4600 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004601 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004602 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004603 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004604 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004605 }
Chao Chen3a137962018-09-19 11:41:27 -07004606#ifdef NV_EXTENSIONS
4607 spv::Id resultStruct = spv::NoResult;
4608 if (imageFootprint) {
4609 //Following three extra arguments
4610 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4611 params.granularity = arguments[2 + extraArgs];
4612 params.coarse = arguments[3 + extraArgs];
4613 resultStruct = arguments[4 + extraArgs];
4614 extraArgs += 3;
4615 }
4616#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004617 // bias
4618 if (bias) {
4619 params.bias = arguments[2 + extraArgs];
4620 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004621 }
John Kessenichfc51d282015-08-19 13:34:18 -06004622
Chao Chen3a137962018-09-19 11:41:27 -07004623#ifdef NV_EXTENSIONS
4624 if (imageFootprint) {
4625 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4626 builder.addCapability(spv::CapabilityImageFootprintNV);
4627
4628
4629 //resultStructType(OpenGL type) contains 5 elements:
4630 //struct gl_TextureFootprint2DNV {
4631 // uvec2 anchor;
4632 // uvec2 offset;
4633 // uvec2 mask;
4634 // uint lod;
4635 // uint granularity;
4636 //};
4637 //or
4638 //struct gl_TextureFootprint3DNV {
4639 // uvec3 anchor;
4640 // uvec3 offset;
4641 // uvec2 mask;
4642 // uint lod;
4643 // uint granularity;
4644 //};
4645 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4646 assert(builder.isStructType(resultStructType));
4647
4648 //resType (SPIR-V type) contains 6 elements:
4649 //Member 0 must be a Boolean type scalar(LOD),
4650 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4651 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4652 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4653 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4654 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4655 std::vector<spv::Id> members;
4656 members.push_back(resultType());
4657 for (int i = 0; i < 5; i++) {
4658 members.push_back(builder.getContainedTypeId(resultStructType, i));
4659 }
4660 spv::Id resType = builder.makeStructType(members, "ResType");
4661
4662 //call ImageFootprintNV
4663 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4664
4665 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4666 for (int i = 0; i < 5; i++) {
4667 builder.clearAccessChain();
4668 builder.setAccessChainLValue(resultStruct);
4669
4670 //Accessing to a struct we created, no coherent flag is set
4671 spv::Builder::AccessChain::CoherentFlags flags;
4672 flags.clear();
4673
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004674 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004675 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4676 }
4677 return builder.createCompositeExtract(res, resultType(), 0);
4678 }
4679#endif
4680
John Kessenich65336482016-06-16 14:06:26 -06004681 // projective component (might not to move)
4682 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4683 // are divided by the last component of P."
4684 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4685 // unused components will appear after all used components."
4686 if (cracked.proj) {
4687 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4688 int projTargetComp;
4689 switch (sampler.dim) {
4690 case glslang::Esd1D: projTargetComp = 1; break;
4691 case glslang::Esd2D: projTargetComp = 2; break;
4692 case glslang::EsdRect: projTargetComp = 2; break;
4693 default: projTargetComp = projSourceComp; break;
4694 }
4695 // copy the projective coordinate if we have to
4696 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004697 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004698 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4699 projSourceComp);
4700 params.coords = builder.createCompositeInsert(projComp, params.coords,
4701 builder.getTypeId(params.coords), projTargetComp);
4702 }
4703 }
4704
Jeff Bolz36831c92018-09-05 10:11:41 -05004705 // nonprivate
4706 if (imageType.getQualifier().nonprivate) {
4707 params.nonprivate = true;
4708 }
4709
4710 // volatile
4711 if (imageType.getQualifier().volatil) {
4712 params.volatil = true;
4713 }
4714
St0fFa1184dd2018-04-09 21:08:14 +02004715 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004716 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004717 );
LoopDawg4425f242018-02-18 11:40:01 -07004718
4719 if (components != node->getType().getVectorSize())
4720 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4721
4722 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004723}
4724
4725spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4726{
4727 // Grab the function's pointer from the previously created function
4728 spv::Function* function = functionMap[node->getName().c_str()];
4729 if (! function)
4730 return 0;
4731
4732 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4733 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4734
4735 // See comments in makeFunctions() for details about the semantics for parameter passing.
4736 //
4737 // These imply we need a four step process:
4738 // 1. Evaluate the arguments
4739 // 2. Allocate and make copies of in, out, and inout arguments
4740 // 3. Make the call
4741 // 4. Copy back the results
4742
John Kessenichd3ed90b2018-05-04 11:43:03 -06004743 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004744 std::vector<spv::Builder::AccessChain> lValues;
4745 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004746 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004747 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004748 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004749 // build l-value
4750 builder.clearAccessChain();
4751 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004752 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004753 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004754 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004755 // save l-value
4756 lValues.push_back(builder.getAccessChain());
4757 } else {
4758 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004759 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004760 }
4761 }
4762
4763 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4764 // copy the original into that space.
4765 //
4766 // Also, build up the list of actual arguments to pass in for the call
4767 int lValueCount = 0;
4768 int rValueCount = 0;
4769 std::vector<spv::Id> spvArgs;
4770 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4771 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004772 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004773 builder.setAccessChain(lValues[lValueCount]);
4774 arg = builder.accessChainGetLValue();
4775 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004776 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004777 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004778 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004779 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4780 // need to copy the input into output space
4781 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004782 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004783 builder.clearAccessChain();
4784 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004785 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004786 }
4787 ++lValueCount;
4788 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004789 // process r-value, which involves a copy for a type mismatch
4790 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4791 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4792 builder.clearAccessChain();
4793 builder.setAccessChainLValue(argCopy);
4794 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4795 arg = builder.createLoad(argCopy);
4796 } else
4797 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004798 ++rValueCount;
4799 }
4800 spvArgs.push_back(arg);
4801 }
4802
4803 // 3. Make the call.
4804 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004805 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004806
4807 // 4. Copy back out an "out" arguments.
4808 lValueCount = 0;
4809 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004810 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004811 ++lValueCount;
4812 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004813 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4814 spv::Id copy = builder.createLoad(spvArgs[a]);
4815 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004816 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004817 }
4818 ++lValueCount;
4819 }
4820 }
4821
4822 return result;
4823}
4824
4825// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004826spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004827 spv::Id typeId, spv::Id left, spv::Id right,
4828 glslang::TBasicType typeProxy, bool reduceComparison)
4829{
John Kessenich66011cb2018-03-06 16:12:04 -07004830 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4831 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004832 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004833
4834 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004835 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004836 bool comparison = false;
4837
4838 switch (op) {
4839 case glslang::EOpAdd:
4840 case glslang::EOpAddAssign:
4841 if (isFloat)
4842 binOp = spv::OpFAdd;
4843 else
4844 binOp = spv::OpIAdd;
4845 break;
4846 case glslang::EOpSub:
4847 case glslang::EOpSubAssign:
4848 if (isFloat)
4849 binOp = spv::OpFSub;
4850 else
4851 binOp = spv::OpISub;
4852 break;
4853 case glslang::EOpMul:
4854 case glslang::EOpMulAssign:
4855 if (isFloat)
4856 binOp = spv::OpFMul;
4857 else
4858 binOp = spv::OpIMul;
4859 break;
4860 case glslang::EOpVectorTimesScalar:
4861 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004862 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004863 if (builder.isVector(right))
4864 std::swap(left, right);
4865 assert(builder.isScalar(right));
4866 needMatchingVectors = false;
4867 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004868 } else if (isFloat)
4869 binOp = spv::OpFMul;
4870 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004871 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004872 break;
4873 case glslang::EOpVectorTimesMatrix:
4874 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004875 binOp = spv::OpVectorTimesMatrix;
4876 break;
4877 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004878 binOp = spv::OpMatrixTimesVector;
4879 break;
4880 case glslang::EOpMatrixTimesScalar:
4881 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004882 binOp = spv::OpMatrixTimesScalar;
4883 break;
4884 case glslang::EOpMatrixTimesMatrix:
4885 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004886 binOp = spv::OpMatrixTimesMatrix;
4887 break;
4888 case glslang::EOpOuterProduct:
4889 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004890 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004891 break;
4892
4893 case glslang::EOpDiv:
4894 case glslang::EOpDivAssign:
4895 if (isFloat)
4896 binOp = spv::OpFDiv;
4897 else if (isUnsigned)
4898 binOp = spv::OpUDiv;
4899 else
4900 binOp = spv::OpSDiv;
4901 break;
4902 case glslang::EOpMod:
4903 case glslang::EOpModAssign:
4904 if (isFloat)
4905 binOp = spv::OpFMod;
4906 else if (isUnsigned)
4907 binOp = spv::OpUMod;
4908 else
4909 binOp = spv::OpSMod;
4910 break;
4911 case glslang::EOpRightShift:
4912 case glslang::EOpRightShiftAssign:
4913 if (isUnsigned)
4914 binOp = spv::OpShiftRightLogical;
4915 else
4916 binOp = spv::OpShiftRightArithmetic;
4917 break;
4918 case glslang::EOpLeftShift:
4919 case glslang::EOpLeftShiftAssign:
4920 binOp = spv::OpShiftLeftLogical;
4921 break;
4922 case glslang::EOpAnd:
4923 case glslang::EOpAndAssign:
4924 binOp = spv::OpBitwiseAnd;
4925 break;
4926 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004927 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004928 binOp = spv::OpLogicalAnd;
4929 break;
4930 case glslang::EOpInclusiveOr:
4931 case glslang::EOpInclusiveOrAssign:
4932 binOp = spv::OpBitwiseOr;
4933 break;
4934 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004935 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004936 binOp = spv::OpLogicalOr;
4937 break;
4938 case glslang::EOpExclusiveOr:
4939 case glslang::EOpExclusiveOrAssign:
4940 binOp = spv::OpBitwiseXor;
4941 break;
4942 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004943 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004944 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004945 break;
4946
4947 case glslang::EOpLessThan:
4948 case glslang::EOpGreaterThan:
4949 case glslang::EOpLessThanEqual:
4950 case glslang::EOpGreaterThanEqual:
4951 case glslang::EOpEqual:
4952 case glslang::EOpNotEqual:
4953 case glslang::EOpVectorEqual:
4954 case glslang::EOpVectorNotEqual:
4955 comparison = true;
4956 break;
4957 default:
4958 break;
4959 }
4960
John Kessenich7c1aa102015-10-15 13:29:11 -06004961 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004962 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004963 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004964 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4965 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004966 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004967
4968 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004969 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004970 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004971
qining25262b32016-05-06 17:25:16 -04004972 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004973 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004974 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004975 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004976 }
4977
4978 if (! comparison)
4979 return 0;
4980
John Kessenich7c1aa102015-10-15 13:29:11 -06004981 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004982
John Kessenich4583b612016-08-07 19:14:22 -06004983 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004984 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4985 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004986 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004987 return result;
4988 }
John Kessenich140f3df2015-06-26 16:58:36 -06004989
4990 switch (op) {
4991 case glslang::EOpLessThan:
4992 if (isFloat)
4993 binOp = spv::OpFOrdLessThan;
4994 else if (isUnsigned)
4995 binOp = spv::OpULessThan;
4996 else
4997 binOp = spv::OpSLessThan;
4998 break;
4999 case glslang::EOpGreaterThan:
5000 if (isFloat)
5001 binOp = spv::OpFOrdGreaterThan;
5002 else if (isUnsigned)
5003 binOp = spv::OpUGreaterThan;
5004 else
5005 binOp = spv::OpSGreaterThan;
5006 break;
5007 case glslang::EOpLessThanEqual:
5008 if (isFloat)
5009 binOp = spv::OpFOrdLessThanEqual;
5010 else if (isUnsigned)
5011 binOp = spv::OpULessThanEqual;
5012 else
5013 binOp = spv::OpSLessThanEqual;
5014 break;
5015 case glslang::EOpGreaterThanEqual:
5016 if (isFloat)
5017 binOp = spv::OpFOrdGreaterThanEqual;
5018 else if (isUnsigned)
5019 binOp = spv::OpUGreaterThanEqual;
5020 else
5021 binOp = spv::OpSGreaterThanEqual;
5022 break;
5023 case glslang::EOpEqual:
5024 case glslang::EOpVectorEqual:
5025 if (isFloat)
5026 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005027 else if (isBool)
5028 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005029 else
5030 binOp = spv::OpIEqual;
5031 break;
5032 case glslang::EOpNotEqual:
5033 case glslang::EOpVectorNotEqual:
5034 if (isFloat)
5035 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005036 else if (isBool)
5037 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005038 else
5039 binOp = spv::OpINotEqual;
5040 break;
5041 default:
5042 break;
5043 }
5044
qining25262b32016-05-06 17:25:16 -04005045 if (binOp != spv::OpNop) {
5046 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005047 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005048 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005049 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005050 }
John Kessenich140f3df2015-06-26 16:58:36 -06005051
5052 return 0;
5053}
5054
John Kessenich04bb8a02015-12-12 12:28:14 -07005055//
5056// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5057// These can be any of:
5058//
5059// matrix * scalar
5060// scalar * matrix
5061// matrix * matrix linear algebraic
5062// matrix * vector
5063// vector * matrix
5064// matrix * matrix componentwise
5065// matrix op matrix op in {+, -, /}
5066// matrix op scalar op in {+, -, /}
5067// scalar op matrix op in {+, -, /}
5068//
John Kessenichead86222018-03-28 18:01:20 -06005069spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5070 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005071{
5072 bool firstClass = true;
5073
5074 // First, handle first-class matrix operations (* and matrix/scalar)
5075 switch (op) {
5076 case spv::OpFDiv:
5077 if (builder.isMatrix(left) && builder.isScalar(right)) {
5078 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005079 spv::Id resultType = builder.getTypeId(right);
5080 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005081 op = spv::OpMatrixTimesScalar;
5082 } else
5083 firstClass = false;
5084 break;
5085 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005086 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005087 std::swap(left, right);
5088 assert(builder.isScalar(right));
5089 break;
5090 case spv::OpVectorTimesMatrix:
5091 assert(builder.isVector(left));
5092 assert(builder.isMatrix(right));
5093 break;
5094 case spv::OpMatrixTimesVector:
5095 assert(builder.isMatrix(left));
5096 assert(builder.isVector(right));
5097 break;
5098 case spv::OpMatrixTimesMatrix:
5099 assert(builder.isMatrix(left));
5100 assert(builder.isMatrix(right));
5101 break;
5102 default:
5103 firstClass = false;
5104 break;
5105 }
5106
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005107 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5108 firstClass = true;
5109
qining25262b32016-05-06 17:25:16 -04005110 if (firstClass) {
5111 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005112 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005113 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005114 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005115 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005116
LoopDawg592860c2016-06-09 08:57:35 -06005117 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005118 // The result type of all of them is the same type as the (a) matrix operand.
5119 // The algorithm is to:
5120 // - break the matrix(es) into vectors
5121 // - smear any scalar to a vector
5122 // - do vector operations
5123 // - make a matrix out the vector results
5124 switch (op) {
5125 case spv::OpFAdd:
5126 case spv::OpFSub:
5127 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005128 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005129 case spv::OpFMul:
5130 {
5131 // one time set up...
5132 bool leftMat = builder.isMatrix(left);
5133 bool rightMat = builder.isMatrix(right);
5134 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5135 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5136 spv::Id scalarType = builder.getScalarTypeId(typeId);
5137 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5138 std::vector<spv::Id> results;
5139 spv::Id smearVec = spv::NoResult;
5140 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005141 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005142 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005143 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005144
5145 // do each vector op
5146 for (unsigned int c = 0; c < numCols; ++c) {
5147 std::vector<unsigned int> indexes;
5148 indexes.push_back(c);
5149 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5150 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005151 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005152 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005153 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005154 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005155 }
5156
5157 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005158 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005159 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005160 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005161 }
5162 default:
5163 assert(0);
5164 return spv::NoResult;
5165 }
5166}
5167
John Kessenichead86222018-03-28 18:01:20 -06005168spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5169 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005170{
5171 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005172 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005173 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005174 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5175 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005176
5177 switch (op) {
5178 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005179 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005180 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005181 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005182 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005183 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005184 unaryOp = spv::OpSNegate;
5185 break;
5186
5187 case glslang::EOpLogicalNot:
5188 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005189 unaryOp = spv::OpLogicalNot;
5190 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005191 case glslang::EOpBitwiseNot:
5192 unaryOp = spv::OpNot;
5193 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005194
John Kessenich140f3df2015-06-26 16:58:36 -06005195 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005196 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005197 break;
5198 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005199 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005200 break;
5201 case glslang::EOpTranspose:
5202 unaryOp = spv::OpTranspose;
5203 break;
5204
5205 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005206 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 break;
5208 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
5229
5230 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
5236 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005237 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005238 break;
5239 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 break;
5242 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005243 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005244 break;
5245 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005246 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005247 break;
5248
5249 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005250 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
5255
5256 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005257 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005258 break;
5259 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005260 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005261 break;
5262 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005263 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005264 break;
5265 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005269 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 break;
5271 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005272 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005273 break;
5274
5275 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005279 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005280 break;
5281 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005282 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005288 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005289 break;
5290 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005291 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005292 break;
5293
5294 case glslang::EOpIsNan:
5295 unaryOp = spv::OpIsNan;
5296 break;
5297 case glslang::EOpIsInf:
5298 unaryOp = spv::OpIsInf;
5299 break;
LoopDawg592860c2016-06-09 08:57:35 -06005300 case glslang::EOpIsFinite:
5301 unaryOp = spv::OpIsFinite;
5302 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005303
Rex Xucbc426e2015-12-15 16:03:10 +08005304 case glslang::EOpFloatBitsToInt:
5305 case glslang::EOpFloatBitsToUint:
5306 case glslang::EOpIntBitsToFloat:
5307 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005308 case glslang::EOpDoubleBitsToInt64:
5309 case glslang::EOpDoubleBitsToUint64:
5310 case glslang::EOpInt64BitsToDouble:
5311 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005312 case glslang::EOpFloat16BitsToInt16:
5313 case glslang::EOpFloat16BitsToUint16:
5314 case glslang::EOpInt16BitsToFloat16:
5315 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005316 unaryOp = spv::OpBitcast;
5317 break;
5318
John Kessenich140f3df2015-06-26 16:58:36 -06005319 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005320 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005321 break;
5322 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005323 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005337 case glslang::EOpPackSnorm4x8:
5338 libCall = spv::GLSLstd450PackSnorm4x8;
5339 break;
5340 case glslang::EOpUnpackSnorm4x8:
5341 libCall = spv::GLSLstd450UnpackSnorm4x8;
5342 break;
5343 case glslang::EOpPackUnorm4x8:
5344 libCall = spv::GLSLstd450PackUnorm4x8;
5345 break;
5346 case glslang::EOpUnpackUnorm4x8:
5347 libCall = spv::GLSLstd450UnpackUnorm4x8;
5348 break;
5349 case glslang::EOpPackDouble2x32:
5350 libCall = spv::GLSLstd450PackDouble2x32;
5351 break;
5352 case glslang::EOpUnpackDouble2x32:
5353 libCall = spv::GLSLstd450UnpackDouble2x32;
5354 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005355
Rex Xu8ff43de2016-04-22 16:51:45 +08005356 case glslang::EOpPackInt2x32:
5357 case glslang::EOpUnpackInt2x32:
5358 case glslang::EOpPackUint2x32:
5359 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005360 case glslang::EOpPack16:
5361 case glslang::EOpPack32:
5362 case glslang::EOpPack64:
5363 case glslang::EOpUnpack32:
5364 case glslang::EOpUnpack16:
5365 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005366 case glslang::EOpPackInt2x16:
5367 case glslang::EOpUnpackInt2x16:
5368 case glslang::EOpPackUint2x16:
5369 case glslang::EOpUnpackUint2x16:
5370 case glslang::EOpPackInt4x16:
5371 case glslang::EOpUnpackInt4x16:
5372 case glslang::EOpPackUint4x16:
5373 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005374 case glslang::EOpPackFloat2x16:
5375 case glslang::EOpUnpackFloat2x16:
5376 unaryOp = spv::OpBitcast;
5377 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005378
John Kessenich140f3df2015-06-26 16:58:36 -06005379 case glslang::EOpDPdx:
5380 unaryOp = spv::OpDPdx;
5381 break;
5382 case glslang::EOpDPdy:
5383 unaryOp = spv::OpDPdy;
5384 break;
5385 case glslang::EOpFwidth:
5386 unaryOp = spv::OpFwidth;
5387 break;
5388 case glslang::EOpDPdxFine:
5389 unaryOp = spv::OpDPdxFine;
5390 break;
5391 case glslang::EOpDPdyFine:
5392 unaryOp = spv::OpDPdyFine;
5393 break;
5394 case glslang::EOpFwidthFine:
5395 unaryOp = spv::OpFwidthFine;
5396 break;
5397 case glslang::EOpDPdxCoarse:
5398 unaryOp = spv::OpDPdxCoarse;
5399 break;
5400 case glslang::EOpDPdyCoarse:
5401 unaryOp = spv::OpDPdyCoarse;
5402 break;
5403 case glslang::EOpFwidthCoarse:
5404 unaryOp = spv::OpFwidthCoarse;
5405 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005406 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005407#ifdef AMD_EXTENSIONS
5408 if (typeProxy == glslang::EbtFloat16)
5409 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5410#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005411 libCall = spv::GLSLstd450InterpolateAtCentroid;
5412 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005413 case glslang::EOpAny:
5414 unaryOp = spv::OpAny;
5415 break;
5416 case glslang::EOpAll:
5417 unaryOp = spv::OpAll;
5418 break;
5419
5420 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005421 if (isFloat)
5422 libCall = spv::GLSLstd450FAbs;
5423 else
5424 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005425 break;
5426 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005427 if (isFloat)
5428 libCall = spv::GLSLstd450FSign;
5429 else
5430 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005431 break;
5432
John Kessenichfc51d282015-08-19 13:34:18 -06005433 case glslang::EOpAtomicCounterIncrement:
5434 case glslang::EOpAtomicCounterDecrement:
5435 case glslang::EOpAtomicCounter:
5436 {
5437 // Handle all of the atomics in one place, in createAtomicOperation()
5438 std::vector<spv::Id> operands;
5439 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005440 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005441 }
5442
John Kessenichfc51d282015-08-19 13:34:18 -06005443 case glslang::EOpBitFieldReverse:
5444 unaryOp = spv::OpBitReverse;
5445 break;
5446 case glslang::EOpBitCount:
5447 unaryOp = spv::OpBitCount;
5448 break;
5449 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005450 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005451 break;
5452 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005453 if (isUnsigned)
5454 libCall = spv::GLSLstd450FindUMsb;
5455 else
5456 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005457 break;
5458
Rex Xu574ab042016-04-14 16:53:07 +08005459 case glslang::EOpBallot:
5460 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005461 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005462 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005463 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005464#ifdef AMD_EXTENSIONS
5465 case glslang::EOpMinInvocations:
5466 case glslang::EOpMaxInvocations:
5467 case glslang::EOpAddInvocations:
5468 case glslang::EOpMinInvocationsNonUniform:
5469 case glslang::EOpMaxInvocationsNonUniform:
5470 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005471 case glslang::EOpMinInvocationsInclusiveScan:
5472 case glslang::EOpMaxInvocationsInclusiveScan:
5473 case glslang::EOpAddInvocationsInclusiveScan:
5474 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5475 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5476 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5477 case glslang::EOpMinInvocationsExclusiveScan:
5478 case glslang::EOpMaxInvocationsExclusiveScan:
5479 case glslang::EOpAddInvocationsExclusiveScan:
5480 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5481 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5482 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005483#endif
Rex Xu51596642016-09-21 18:56:12 +08005484 {
5485 std::vector<spv::Id> operands;
5486 operands.push_back(operand);
5487 return createInvocationsOperation(op, typeId, operands, typeProxy);
5488 }
John Kessenich66011cb2018-03-06 16:12:04 -07005489 case glslang::EOpSubgroupAll:
5490 case glslang::EOpSubgroupAny:
5491 case glslang::EOpSubgroupAllEqual:
5492 case glslang::EOpSubgroupBroadcastFirst:
5493 case glslang::EOpSubgroupBallot:
5494 case glslang::EOpSubgroupInverseBallot:
5495 case glslang::EOpSubgroupBallotBitCount:
5496 case glslang::EOpSubgroupBallotInclusiveBitCount:
5497 case glslang::EOpSubgroupBallotExclusiveBitCount:
5498 case glslang::EOpSubgroupBallotFindLSB:
5499 case glslang::EOpSubgroupBallotFindMSB:
5500 case glslang::EOpSubgroupAdd:
5501 case glslang::EOpSubgroupMul:
5502 case glslang::EOpSubgroupMin:
5503 case glslang::EOpSubgroupMax:
5504 case glslang::EOpSubgroupAnd:
5505 case glslang::EOpSubgroupOr:
5506 case glslang::EOpSubgroupXor:
5507 case glslang::EOpSubgroupInclusiveAdd:
5508 case glslang::EOpSubgroupInclusiveMul:
5509 case glslang::EOpSubgroupInclusiveMin:
5510 case glslang::EOpSubgroupInclusiveMax:
5511 case glslang::EOpSubgroupInclusiveAnd:
5512 case glslang::EOpSubgroupInclusiveOr:
5513 case glslang::EOpSubgroupInclusiveXor:
5514 case glslang::EOpSubgroupExclusiveAdd:
5515 case glslang::EOpSubgroupExclusiveMul:
5516 case glslang::EOpSubgroupExclusiveMin:
5517 case glslang::EOpSubgroupExclusiveMax:
5518 case glslang::EOpSubgroupExclusiveAnd:
5519 case glslang::EOpSubgroupExclusiveOr:
5520 case glslang::EOpSubgroupExclusiveXor:
5521 case glslang::EOpSubgroupQuadSwapHorizontal:
5522 case glslang::EOpSubgroupQuadSwapVertical:
5523 case glslang::EOpSubgroupQuadSwapDiagonal: {
5524 std::vector<spv::Id> operands;
5525 operands.push_back(operand);
5526 return createSubgroupOperation(op, typeId, operands, typeProxy);
5527 }
Rex Xu9d93a232016-05-05 12:30:44 +08005528#ifdef AMD_EXTENSIONS
5529 case glslang::EOpMbcnt:
5530 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5531 libCall = spv::MbcntAMD;
5532 break;
5533
5534 case glslang::EOpCubeFaceIndex:
5535 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5536 libCall = spv::CubeFaceIndexAMD;
5537 break;
5538
5539 case glslang::EOpCubeFaceCoord:
5540 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5541 libCall = spv::CubeFaceCoordAMD;
5542 break;
5543#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005544#ifdef NV_EXTENSIONS
5545 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005546 unaryOp = spv::OpGroupNonUniformPartitionNV;
5547 break;
5548#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005549 case glslang::EOpConstructReference:
5550 unaryOp = spv::OpBitcast;
5551 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005552
5553 case glslang::EOpCopyObject:
5554 unaryOp = spv::OpCopyObject;
5555 break;
5556
John Kessenich140f3df2015-06-26 16:58:36 -06005557 default:
5558 return 0;
5559 }
5560
5561 spv::Id id;
5562 if (libCall >= 0) {
5563 std::vector<spv::Id> args;
5564 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005565 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005566 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005567 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005568 }
John Kessenich140f3df2015-06-26 16:58:36 -06005569
John Kessenichead86222018-03-28 18:01:20 -06005570 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005571 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005572 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005573}
5574
John Kessenich7a53f762016-01-20 11:19:27 -07005575// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005576spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5577 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005578{
5579 // Handle unary operations vector by vector.
5580 // The result type is the same type as the original type.
5581 // The algorithm is to:
5582 // - break the matrix into vectors
5583 // - apply the operation to each vector
5584 // - make a matrix out the vector results
5585
5586 // get the types sorted out
5587 int numCols = builder.getNumColumns(operand);
5588 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005589 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5590 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005591 std::vector<spv::Id> results;
5592
5593 // do each vector op
5594 for (int c = 0; c < numCols; ++c) {
5595 std::vector<unsigned int> indexes;
5596 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005597 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5598 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005599 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005600 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005601 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005602 }
5603
5604 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005605 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005606 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005607 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005608}
5609
John Kessenichad7645f2018-06-04 19:11:25 -06005610// For converting integers where both the bitwidth and the signedness could
5611// change, but only do the width change here. The caller is still responsible
5612// for the signedness conversion.
5613spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005614{
John Kessenichad7645f2018-06-04 19:11:25 -06005615 // Get the result type width, based on the type to convert to.
5616 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005617 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005618 case glslang::EOpConvInt16ToUint8:
5619 case glslang::EOpConvIntToUint8:
5620 case glslang::EOpConvInt64ToUint8:
5621 case glslang::EOpConvUint16ToInt8:
5622 case glslang::EOpConvUintToInt8:
5623 case glslang::EOpConvUint64ToInt8:
5624 width = 8;
5625 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005626 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005627 case glslang::EOpConvIntToUint16:
5628 case glslang::EOpConvInt64ToUint16:
5629 case glslang::EOpConvUint8ToInt16:
5630 case glslang::EOpConvUintToInt16:
5631 case glslang::EOpConvUint64ToInt16:
5632 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005633 break;
5634 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005635 case glslang::EOpConvInt16ToUint:
5636 case glslang::EOpConvInt64ToUint:
5637 case glslang::EOpConvUint8ToInt:
5638 case glslang::EOpConvUint16ToInt:
5639 case glslang::EOpConvUint64ToInt:
5640 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005641 break;
5642 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005643 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005644 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005645 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005646 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005647 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005648 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005649 break;
5650
5651 default:
5652 assert(false && "Default missing");
5653 break;
5654 }
5655
John Kessenichad7645f2018-06-04 19:11:25 -06005656 // Get the conversion operation and result type,
5657 // based on the target width, but the source type.
5658 spv::Id type = spv::NoType;
5659 spv::Op convOp = spv::OpNop;
5660 switch(op) {
5661 case glslang::EOpConvInt8ToUint16:
5662 case glslang::EOpConvInt8ToUint:
5663 case glslang::EOpConvInt8ToUint64:
5664 case glslang::EOpConvInt16ToUint8:
5665 case glslang::EOpConvInt16ToUint:
5666 case glslang::EOpConvInt16ToUint64:
5667 case glslang::EOpConvIntToUint8:
5668 case glslang::EOpConvIntToUint16:
5669 case glslang::EOpConvIntToUint64:
5670 case glslang::EOpConvInt64ToUint8:
5671 case glslang::EOpConvInt64ToUint16:
5672 case glslang::EOpConvInt64ToUint:
5673 convOp = spv::OpSConvert;
5674 type = builder.makeIntType(width);
5675 break;
5676 default:
5677 convOp = spv::OpUConvert;
5678 type = builder.makeUintType(width);
5679 break;
5680 }
5681
John Kessenich66011cb2018-03-06 16:12:04 -07005682 if (vectorSize > 0)
5683 type = builder.makeVectorType(type, vectorSize);
5684
John Kessenichad7645f2018-06-04 19:11:25 -06005685 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005686}
5687
John Kessenichead86222018-03-28 18:01:20 -06005688spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5689 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005690{
5691 spv::Op convOp = spv::OpNop;
5692 spv::Id zero = 0;
5693 spv::Id one = 0;
5694
5695 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5696
5697 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005698 case glslang::EOpConvInt8ToBool:
5699 case glslang::EOpConvUint8ToBool:
5700 zero = builder.makeUint8Constant(0);
5701 zero = makeSmearedConstant(zero, vectorSize);
5702 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005703 case glslang::EOpConvInt16ToBool:
5704 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005705 zero = builder.makeUint16Constant(0);
5706 zero = makeSmearedConstant(zero, vectorSize);
5707 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5708 case glslang::EOpConvIntToBool:
5709 case glslang::EOpConvUintToBool:
5710 zero = builder.makeUintConstant(0);
5711 zero = makeSmearedConstant(zero, vectorSize);
5712 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5713 case glslang::EOpConvInt64ToBool:
5714 case glslang::EOpConvUint64ToBool:
5715 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005716 zero = makeSmearedConstant(zero, vectorSize);
5717 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5718
5719 case glslang::EOpConvFloatToBool:
5720 zero = builder.makeFloatConstant(0.0F);
5721 zero = makeSmearedConstant(zero, vectorSize);
5722 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5723
5724 case glslang::EOpConvDoubleToBool:
5725 zero = builder.makeDoubleConstant(0.0);
5726 zero = makeSmearedConstant(zero, vectorSize);
5727 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5728
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005729 case glslang::EOpConvFloat16ToBool:
5730 zero = builder.makeFloat16Constant(0.0F);
5731 zero = makeSmearedConstant(zero, vectorSize);
5732 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005733
John Kessenich140f3df2015-06-26 16:58:36 -06005734 case glslang::EOpConvBoolToFloat:
5735 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005736 zero = builder.makeFloatConstant(0.0F);
5737 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005738 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005739
John Kessenich140f3df2015-06-26 16:58:36 -06005740 case glslang::EOpConvBoolToDouble:
5741 convOp = spv::OpSelect;
5742 zero = builder.makeDoubleConstant(0.0);
5743 one = builder.makeDoubleConstant(1.0);
5744 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005745
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005746 case glslang::EOpConvBoolToFloat16:
5747 convOp = spv::OpSelect;
5748 zero = builder.makeFloat16Constant(0.0F);
5749 one = builder.makeFloat16Constant(1.0F);
5750 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005751
5752 case glslang::EOpConvBoolToInt8:
5753 zero = builder.makeInt8Constant(0);
5754 one = builder.makeInt8Constant(1);
5755 convOp = spv::OpSelect;
5756 break;
5757
5758 case glslang::EOpConvBoolToUint8:
5759 zero = builder.makeUint8Constant(0);
5760 one = builder.makeUint8Constant(1);
5761 convOp = spv::OpSelect;
5762 break;
5763
5764 case glslang::EOpConvBoolToInt16:
5765 zero = builder.makeInt16Constant(0);
5766 one = builder.makeInt16Constant(1);
5767 convOp = spv::OpSelect;
5768 break;
5769
5770 case glslang::EOpConvBoolToUint16:
5771 zero = builder.makeUint16Constant(0);
5772 one = builder.makeUint16Constant(1);
5773 convOp = spv::OpSelect;
5774 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005775
John Kessenich140f3df2015-06-26 16:58:36 -06005776 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005777 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005778 if (op == glslang::EOpConvBoolToInt64)
5779 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005780 else
5781 zero = builder.makeIntConstant(0);
5782
5783 if (op == glslang::EOpConvBoolToInt64)
5784 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005785 else
5786 one = builder.makeIntConstant(1);
5787
John Kessenich140f3df2015-06-26 16:58:36 -06005788 convOp = spv::OpSelect;
5789 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005790
John Kessenich140f3df2015-06-26 16:58:36 -06005791 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005792 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005793 if (op == glslang::EOpConvBoolToUint64)
5794 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005795 else
5796 zero = builder.makeUintConstant(0);
5797
5798 if (op == glslang::EOpConvBoolToUint64)
5799 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005800 else
5801 one = builder.makeUintConstant(1);
5802
John Kessenich140f3df2015-06-26 16:58:36 -06005803 convOp = spv::OpSelect;
5804 break;
5805
John Kessenich66011cb2018-03-06 16:12:04 -07005806 case glslang::EOpConvInt8ToFloat16:
5807 case glslang::EOpConvInt8ToFloat:
5808 case glslang::EOpConvInt8ToDouble:
5809 case glslang::EOpConvInt16ToFloat16:
5810 case glslang::EOpConvInt16ToFloat:
5811 case glslang::EOpConvInt16ToDouble:
5812 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005813 case glslang::EOpConvIntToFloat:
5814 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005815 case glslang::EOpConvInt64ToFloat:
5816 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005817 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005818 convOp = spv::OpConvertSToF;
5819 break;
5820
John Kessenich66011cb2018-03-06 16:12:04 -07005821 case glslang::EOpConvUint8ToFloat16:
5822 case glslang::EOpConvUint8ToFloat:
5823 case glslang::EOpConvUint8ToDouble:
5824 case glslang::EOpConvUint16ToFloat16:
5825 case glslang::EOpConvUint16ToFloat:
5826 case glslang::EOpConvUint16ToDouble:
5827 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005828 case glslang::EOpConvUintToFloat:
5829 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005830 case glslang::EOpConvUint64ToFloat:
5831 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005832 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005833 convOp = spv::OpConvertUToF;
5834 break;
5835
5836 case glslang::EOpConvDoubleToFloat:
5837 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005838 case glslang::EOpConvDoubleToFloat16:
5839 case glslang::EOpConvFloat16ToDouble:
5840 case glslang::EOpConvFloatToFloat16:
5841 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005842 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005843 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005844 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846
John Kessenich66011cb2018-03-06 16:12:04 -07005847 case glslang::EOpConvFloat16ToInt8:
5848 case glslang::EOpConvFloatToInt8:
5849 case glslang::EOpConvDoubleToInt8:
5850 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005851 case glslang::EOpConvFloatToInt16:
5852 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005853 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005854 case glslang::EOpConvFloatToInt:
5855 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005856 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005857 case glslang::EOpConvFloatToInt64:
5858 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005859 convOp = spv::OpConvertFToS;
5860 break;
5861
John Kessenich66011cb2018-03-06 16:12:04 -07005862 case glslang::EOpConvUint8ToInt8:
5863 case glslang::EOpConvInt8ToUint8:
5864 case glslang::EOpConvUint16ToInt16:
5865 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005866 case glslang::EOpConvUintToInt:
5867 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005868 case glslang::EOpConvUint64ToInt64:
5869 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005870 if (builder.isInSpecConstCodeGenMode()) {
5871 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005872 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5873 zero = builder.makeUint8Constant(0);
5874 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005875 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005876 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5877 zero = builder.makeUint64Constant(0);
5878 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005879 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005880 }
qining189b2032016-04-12 23:16:20 -04005881 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005882 // Use OpIAdd, instead of OpBitcast to do the conversion when
5883 // generating for OpSpecConstantOp instruction.
5884 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5885 }
5886 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005887 convOp = spv::OpBitcast;
5888 break;
5889
John Kessenich66011cb2018-03-06 16:12:04 -07005890 case glslang::EOpConvFloat16ToUint8:
5891 case glslang::EOpConvFloatToUint8:
5892 case glslang::EOpConvDoubleToUint8:
5893 case glslang::EOpConvFloat16ToUint16:
5894 case glslang::EOpConvFloatToUint16:
5895 case glslang::EOpConvDoubleToUint16:
5896 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005897 case glslang::EOpConvFloatToUint:
5898 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005899 case glslang::EOpConvFloatToUint64:
5900 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005901 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005902 convOp = spv::OpConvertFToU;
5903 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005904
John Kessenich66011cb2018-03-06 16:12:04 -07005905 case glslang::EOpConvInt8ToInt16:
5906 case glslang::EOpConvInt8ToInt:
5907 case glslang::EOpConvInt8ToInt64:
5908 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005909 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005910 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005911 case glslang::EOpConvIntToInt8:
5912 case glslang::EOpConvIntToInt16:
5913 case glslang::EOpConvIntToInt64:
5914 case glslang::EOpConvInt64ToInt8:
5915 case glslang::EOpConvInt64ToInt16:
5916 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005917 convOp = spv::OpSConvert;
5918 break;
5919
John Kessenich66011cb2018-03-06 16:12:04 -07005920 case glslang::EOpConvUint8ToUint16:
5921 case glslang::EOpConvUint8ToUint:
5922 case glslang::EOpConvUint8ToUint64:
5923 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005924 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005925 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005926 case glslang::EOpConvUintToUint8:
5927 case glslang::EOpConvUintToUint16:
5928 case glslang::EOpConvUintToUint64:
5929 case glslang::EOpConvUint64ToUint8:
5930 case glslang::EOpConvUint64ToUint16:
5931 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005932 convOp = spv::OpUConvert;
5933 break;
5934
John Kessenich66011cb2018-03-06 16:12:04 -07005935 case glslang::EOpConvInt8ToUint16:
5936 case glslang::EOpConvInt8ToUint:
5937 case glslang::EOpConvInt8ToUint64:
5938 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005939 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005940 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005941 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005942 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005943 case glslang::EOpConvIntToUint64:
5944 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005945 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005946 case glslang::EOpConvInt64ToUint:
5947 case glslang::EOpConvUint8ToInt16:
5948 case glslang::EOpConvUint8ToInt:
5949 case glslang::EOpConvUint8ToInt64:
5950 case glslang::EOpConvUint16ToInt8:
5951 case glslang::EOpConvUint16ToInt:
5952 case glslang::EOpConvUint16ToInt64:
5953 case glslang::EOpConvUintToInt8:
5954 case glslang::EOpConvUintToInt16:
5955 case glslang::EOpConvUintToInt64:
5956 case glslang::EOpConvUint64ToInt8:
5957 case glslang::EOpConvUint64ToInt16:
5958 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005959 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005960 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005961
5962 if (builder.isInSpecConstCodeGenMode()) {
5963 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005964 switch(op) {
5965 case glslang::EOpConvInt16ToUint8:
5966 case glslang::EOpConvIntToUint8:
5967 case glslang::EOpConvInt64ToUint8:
5968 case glslang::EOpConvUint16ToInt8:
5969 case glslang::EOpConvUintToInt8:
5970 case glslang::EOpConvUint64ToInt8:
5971 zero = builder.makeUint8Constant(0);
5972 break;
5973 case glslang::EOpConvInt8ToUint16:
5974 case glslang::EOpConvIntToUint16:
5975 case glslang::EOpConvInt64ToUint16:
5976 case glslang::EOpConvUint8ToInt16:
5977 case glslang::EOpConvUintToInt16:
5978 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005979 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005980 break;
5981 case glslang::EOpConvInt8ToUint:
5982 case glslang::EOpConvInt16ToUint:
5983 case glslang::EOpConvInt64ToUint:
5984 case glslang::EOpConvUint8ToInt:
5985 case glslang::EOpConvUint16ToInt:
5986 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005987 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005988 break;
5989 case glslang::EOpConvInt8ToUint64:
5990 case glslang::EOpConvInt16ToUint64:
5991 case glslang::EOpConvIntToUint64:
5992 case glslang::EOpConvUint8ToInt64:
5993 case glslang::EOpConvUint16ToInt64:
5994 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005995 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005996 break;
5997 default:
5998 assert(false && "Default missing");
5999 break;
6000 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006001 zero = makeSmearedConstant(zero, vectorSize);
6002 // Use OpIAdd, instead of OpBitcast to do the conversion when
6003 // generating for OpSpecConstantOp instruction.
6004 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6005 }
6006 // For normal run-time conversion instruction, use OpBitcast.
6007 convOp = spv::OpBitcast;
6008 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006009 case glslang::EOpConvUint64ToPtr:
6010 convOp = spv::OpConvertUToPtr;
6011 break;
6012 case glslang::EOpConvPtrToUint64:
6013 convOp = spv::OpConvertPtrToU;
6014 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 default:
6016 break;
6017 }
6018
6019 spv::Id result = 0;
6020 if (convOp == spv::OpNop)
6021 return result;
6022
6023 if (convOp == spv::OpSelect) {
6024 zero = makeSmearedConstant(zero, vectorSize);
6025 one = makeSmearedConstant(one, vectorSize);
6026 result = builder.createTriOp(convOp, destType, operand, one, zero);
6027 } else
6028 result = builder.createUnaryOp(convOp, destType, operand);
6029
John Kessenichead86222018-03-28 18:01:20 -06006030 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006031 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006032 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006033}
6034
6035spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6036{
6037 if (vectorSize == 0)
6038 return constant;
6039
6040 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6041 std::vector<spv::Id> components;
6042 for (int c = 0; c < vectorSize; ++c)
6043 components.push_back(constant);
6044 return builder.makeCompositeConstant(vectorTypeId, components);
6045}
6046
John Kessenich426394d2015-07-23 10:22:48 -06006047// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006048spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06006049{
6050 spv::Op opCode = spv::OpNop;
6051
6052 switch (op) {
6053 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006054 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006055 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006056 opCode = spv::OpAtomicIAdd;
6057 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006058 case glslang::EOpAtomicCounterSubtract:
6059 opCode = spv::OpAtomicISub;
6060 break;
John Kessenich426394d2015-07-23 10:22:48 -06006061 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006062 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006063 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006064 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006065 break;
6066 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006067 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006068 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006069 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006070 break;
6071 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006072 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006073 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006074 opCode = spv::OpAtomicAnd;
6075 break;
6076 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006077 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006078 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006079 opCode = spv::OpAtomicOr;
6080 break;
6081 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006082 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006083 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006084 opCode = spv::OpAtomicXor;
6085 break;
6086 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006087 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006088 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006089 opCode = spv::OpAtomicExchange;
6090 break;
6091 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006092 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006093 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006094 opCode = spv::OpAtomicCompareExchange;
6095 break;
6096 case glslang::EOpAtomicCounterIncrement:
6097 opCode = spv::OpAtomicIIncrement;
6098 break;
6099 case glslang::EOpAtomicCounterDecrement:
6100 opCode = spv::OpAtomicIDecrement;
6101 break;
6102 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006103 case glslang::EOpImageAtomicLoad:
6104 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006105 opCode = spv::OpAtomicLoad;
6106 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006107 case glslang::EOpAtomicStore:
6108 case glslang::EOpImageAtomicStore:
6109 opCode = spv::OpAtomicStore;
6110 break;
John Kessenich426394d2015-07-23 10:22:48 -06006111 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006112 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006113 break;
6114 }
6115
Rex Xue8fe8b02017-09-26 15:42:56 +08006116 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6117 builder.addCapability(spv::CapabilityInt64Atomics);
6118
John Kessenich426394d2015-07-23 10:22:48 -06006119 // Sort out the operands
6120 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006121 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006122 // - compare-exchange swaps the value and comparator
6123 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006124 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006125 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6126 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6127 spv::Id scopeId;
6128 if (glslangIntermediate->usingVulkanMemoryModel()) {
6129 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6130 } else {
6131 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6132 }
6133 // semantics default to relaxed
6134 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6135 spv::Id semanticsId2 = semanticsId;
6136
6137 pointerId = operands[0];
6138 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6139 // no additional operands
6140 } else if (opCode == spv::OpAtomicCompareExchange) {
6141 compareId = operands[1];
6142 valueId = operands[2];
6143 if (operands.size() > 3) {
6144 scopeId = operands[3];
6145 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6146 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6147 }
6148 } else if (opCode == spv::OpAtomicLoad) {
6149 if (operands.size() > 1) {
6150 scopeId = operands[1];
6151 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6152 }
6153 } else {
6154 // atomic store or RMW
6155 valueId = operands[1];
6156 if (operands.size() > 2) {
6157 scopeId = operands[2];
6158 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6159 }
Rex Xu04db3f52015-09-16 11:44:02 +08006160 }
John Kessenich426394d2015-07-23 10:22:48 -06006161
Jeff Bolz36831c92018-09-05 10:11:41 -05006162 // Check for capabilities
6163 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6164 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6165 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6166 }
John Kessenich426394d2015-07-23 10:22:48 -06006167
Jeff Bolz36831c92018-09-05 10:11:41 -05006168 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6169 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6170 }
John Kessenich48d6e792017-10-06 21:21:48 -06006171
Jeff Bolz36831c92018-09-05 10:11:41 -05006172 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6173 spvAtomicOperands.push_back(pointerId);
6174 spvAtomicOperands.push_back(scopeId);
6175 spvAtomicOperands.push_back(semanticsId);
6176 if (opCode == spv::OpAtomicCompareExchange) {
6177 spvAtomicOperands.push_back(semanticsId2);
6178 spvAtomicOperands.push_back(valueId);
6179 spvAtomicOperands.push_back(compareId);
6180 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6181 spvAtomicOperands.push_back(valueId);
6182 }
John Kessenich48d6e792017-10-06 21:21:48 -06006183
Jeff Bolz36831c92018-09-05 10:11:41 -05006184 if (opCode == spv::OpAtomicStore) {
6185 builder.createNoResultOp(opCode, spvAtomicOperands);
6186 return 0;
6187 } else {
6188 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6189
6190 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6191 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6192 if (op == glslang::EOpAtomicCounterDecrement)
6193 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6194
6195 return resultId;
6196 }
John Kessenich426394d2015-07-23 10:22:48 -06006197}
6198
John Kessenich91cef522016-05-05 16:45:40 -06006199// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006200spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006201{
Corentin Walleze7061422018-08-08 15:20:15 +02006202#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006203 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6204 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006205#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006206
Rex Xu51596642016-09-21 18:56:12 +08006207 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006208 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006209 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6210
chaocf200da82016-12-20 12:44:35 -08006211 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6212 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006213 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6214 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006215 } else if (op == glslang::EOpAnyInvocation ||
6216 op == glslang::EOpAllInvocations ||
6217 op == glslang::EOpAllInvocationsEqual) {
6218 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6219 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006220 } else {
6221 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006222#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006223 if (op == glslang::EOpMinInvocationsNonUniform ||
6224 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006225 op == glslang::EOpAddInvocationsNonUniform ||
6226 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6227 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6228 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6229 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6230 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6231 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006232 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006233#endif
Rex Xu51596642016-09-21 18:56:12 +08006234
Rex Xu9d93a232016-05-05 12:30:44 +08006235#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006236 switch (op) {
6237 case glslang::EOpMinInvocations:
6238 case glslang::EOpMaxInvocations:
6239 case glslang::EOpAddInvocations:
6240 case glslang::EOpMinInvocationsNonUniform:
6241 case glslang::EOpMaxInvocationsNonUniform:
6242 case glslang::EOpAddInvocationsNonUniform:
6243 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006244 break;
6245 case glslang::EOpMinInvocationsInclusiveScan:
6246 case glslang::EOpMaxInvocationsInclusiveScan:
6247 case glslang::EOpAddInvocationsInclusiveScan:
6248 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6249 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6250 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6251 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006252 break;
6253 case glslang::EOpMinInvocationsExclusiveScan:
6254 case glslang::EOpMaxInvocationsExclusiveScan:
6255 case glslang::EOpAddInvocationsExclusiveScan:
6256 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6257 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6258 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6259 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006260 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006261 default:
6262 break;
Rex Xu430ef402016-10-14 17:22:23 +08006263 }
John Kessenich149afc32018-08-14 13:31:43 -06006264 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6265 spvGroupOperands.push_back(scope);
6266 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006267 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006268 spvGroupOperands.push_back(groupOp);
6269 }
Rex Xu9d93a232016-05-05 12:30:44 +08006270#endif
Rex Xu51596642016-09-21 18:56:12 +08006271 }
6272
John Kessenich149afc32018-08-14 13:31:43 -06006273 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6274 spv::IdImmediate op = { true, *opIt };
6275 spvGroupOperands.push_back(op);
6276 }
John Kessenich91cef522016-05-05 16:45:40 -06006277
6278 switch (op) {
6279 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006280 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006281 break;
John Kessenich91cef522016-05-05 16:45:40 -06006282 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006283 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006284 break;
John Kessenich91cef522016-05-05 16:45:40 -06006285 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006286 opCode = spv::OpSubgroupAllEqualKHR;
6287 break;
Rex Xu51596642016-09-21 18:56:12 +08006288 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006289 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006290 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006291 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006292 break;
6293 case glslang::EOpReadFirstInvocation:
6294 opCode = spv::OpSubgroupFirstInvocationKHR;
6295 break;
6296 case glslang::EOpBallot:
6297 {
6298 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6299 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6300 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6301 //
6302 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6303 //
6304 spv::Id uintType = builder.makeUintType(32);
6305 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6306 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6307
6308 std::vector<spv::Id> components;
6309 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6310 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6311
6312 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6313 return builder.createUnaryOp(spv::OpBitcast, typeId,
6314 builder.createCompositeConstruct(uvec2Type, components));
6315 }
6316
Rex Xu9d93a232016-05-05 12:30:44 +08006317#ifdef AMD_EXTENSIONS
6318 case glslang::EOpMinInvocations:
6319 case glslang::EOpMaxInvocations:
6320 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006321 case glslang::EOpMinInvocationsInclusiveScan:
6322 case glslang::EOpMaxInvocationsInclusiveScan:
6323 case glslang::EOpAddInvocationsInclusiveScan:
6324 case glslang::EOpMinInvocationsExclusiveScan:
6325 case glslang::EOpMaxInvocationsExclusiveScan:
6326 case glslang::EOpAddInvocationsExclusiveScan:
6327 if (op == glslang::EOpMinInvocations ||
6328 op == glslang::EOpMinInvocationsInclusiveScan ||
6329 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006330 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006331 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006332 else {
6333 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006334 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006335 else
Rex Xu51596642016-09-21 18:56:12 +08006336 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006337 }
Rex Xu430ef402016-10-14 17:22:23 +08006338 } else if (op == glslang::EOpMaxInvocations ||
6339 op == glslang::EOpMaxInvocationsInclusiveScan ||
6340 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006341 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006342 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006343 else {
6344 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006345 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006346 else
Rex Xu51596642016-09-21 18:56:12 +08006347 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006348 }
6349 } else {
6350 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006351 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006352 else
Rex Xu51596642016-09-21 18:56:12 +08006353 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006354 }
6355
Rex Xu2bbbe062016-08-23 15:41:05 +08006356 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006357 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006358
6359 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006360 case glslang::EOpMinInvocationsNonUniform:
6361 case glslang::EOpMaxInvocationsNonUniform:
6362 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006363 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6364 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6365 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6366 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6367 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6368 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6369 if (op == glslang::EOpMinInvocationsNonUniform ||
6370 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6371 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006372 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006373 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006374 else {
6375 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006376 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006377 else
Rex Xu51596642016-09-21 18:56:12 +08006378 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006379 }
6380 }
Rex Xu430ef402016-10-14 17:22:23 +08006381 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6382 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6383 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006384 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006385 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006386 else {
6387 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006388 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006389 else
Rex Xu51596642016-09-21 18:56:12 +08006390 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006391 }
6392 }
6393 else {
6394 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006395 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006396 else
Rex Xu51596642016-09-21 18:56:12 +08006397 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006398 }
6399
Rex Xu2bbbe062016-08-23 15:41:05 +08006400 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006401 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006402
6403 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006404#endif
John Kessenich91cef522016-05-05 16:45:40 -06006405 default:
6406 logger->missingFunctionality("invocation operation");
6407 return spv::NoResult;
6408 }
Rex Xu51596642016-09-21 18:56:12 +08006409
6410 assert(opCode != spv::OpNop);
6411 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006412}
6413
Rex Xu2bbbe062016-08-23 15:41:05 +08006414// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006415spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6416 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006417{
Rex Xub7072052016-09-26 15:53:40 +08006418#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006419 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6420 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006421 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006422 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006423 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6424 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6425 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006426#else
6427 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6428 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006429 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6430 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006431#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006432
6433 // Handle group invocation operations scalar by scalar.
6434 // The result type is the same type as the original type.
6435 // The algorithm is to:
6436 // - break the vector into scalars
6437 // - apply the operation to each scalar
6438 // - make a vector out the scalar results
6439
6440 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006441 int numComponents = builder.getNumComponents(operands[0]);
6442 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006443 std::vector<spv::Id> results;
6444
6445 // do each scalar op
6446 for (int comp = 0; comp < numComponents; ++comp) {
6447 std::vector<unsigned int> indexes;
6448 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006449 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6450 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006451 if (op == spv::OpSubgroupReadInvocationKHR) {
6452 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006453 spv::IdImmediate operand = { true, operands[1] };
6454 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006455 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006456 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6457 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006458 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006459 spv::IdImmediate operand = { true, operands[1] };
6460 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006461 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006462 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6463 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006464 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006465 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006466 spvGroupOperands.push_back(scalar);
6467 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006468
Rex Xub7072052016-09-26 15:53:40 +08006469 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006470 }
6471
6472 // put the pieces together
6473 return builder.createCompositeConstruct(typeId, results);
6474}
Rex Xu2bbbe062016-08-23 15:41:05 +08006475
John Kessenich66011cb2018-03-06 16:12:04 -07006476// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006477spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6478 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006479{
6480 // Add the required capabilities.
6481 switch (op) {
6482 case glslang::EOpSubgroupElect:
6483 builder.addCapability(spv::CapabilityGroupNonUniform);
6484 break;
6485 case glslang::EOpSubgroupAll:
6486 case glslang::EOpSubgroupAny:
6487 case glslang::EOpSubgroupAllEqual:
6488 builder.addCapability(spv::CapabilityGroupNonUniform);
6489 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6490 break;
6491 case glslang::EOpSubgroupBroadcast:
6492 case glslang::EOpSubgroupBroadcastFirst:
6493 case glslang::EOpSubgroupBallot:
6494 case glslang::EOpSubgroupInverseBallot:
6495 case glslang::EOpSubgroupBallotBitExtract:
6496 case glslang::EOpSubgroupBallotBitCount:
6497 case glslang::EOpSubgroupBallotInclusiveBitCount:
6498 case glslang::EOpSubgroupBallotExclusiveBitCount:
6499 case glslang::EOpSubgroupBallotFindLSB:
6500 case glslang::EOpSubgroupBallotFindMSB:
6501 builder.addCapability(spv::CapabilityGroupNonUniform);
6502 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6503 break;
6504 case glslang::EOpSubgroupShuffle:
6505 case glslang::EOpSubgroupShuffleXor:
6506 builder.addCapability(spv::CapabilityGroupNonUniform);
6507 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6508 break;
6509 case glslang::EOpSubgroupShuffleUp:
6510 case glslang::EOpSubgroupShuffleDown:
6511 builder.addCapability(spv::CapabilityGroupNonUniform);
6512 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6513 break;
6514 case glslang::EOpSubgroupAdd:
6515 case glslang::EOpSubgroupMul:
6516 case glslang::EOpSubgroupMin:
6517 case glslang::EOpSubgroupMax:
6518 case glslang::EOpSubgroupAnd:
6519 case glslang::EOpSubgroupOr:
6520 case glslang::EOpSubgroupXor:
6521 case glslang::EOpSubgroupInclusiveAdd:
6522 case glslang::EOpSubgroupInclusiveMul:
6523 case glslang::EOpSubgroupInclusiveMin:
6524 case glslang::EOpSubgroupInclusiveMax:
6525 case glslang::EOpSubgroupInclusiveAnd:
6526 case glslang::EOpSubgroupInclusiveOr:
6527 case glslang::EOpSubgroupInclusiveXor:
6528 case glslang::EOpSubgroupExclusiveAdd:
6529 case glslang::EOpSubgroupExclusiveMul:
6530 case glslang::EOpSubgroupExclusiveMin:
6531 case glslang::EOpSubgroupExclusiveMax:
6532 case glslang::EOpSubgroupExclusiveAnd:
6533 case glslang::EOpSubgroupExclusiveOr:
6534 case glslang::EOpSubgroupExclusiveXor:
6535 builder.addCapability(spv::CapabilityGroupNonUniform);
6536 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6537 break;
6538 case glslang::EOpSubgroupClusteredAdd:
6539 case glslang::EOpSubgroupClusteredMul:
6540 case glslang::EOpSubgroupClusteredMin:
6541 case glslang::EOpSubgroupClusteredMax:
6542 case glslang::EOpSubgroupClusteredAnd:
6543 case glslang::EOpSubgroupClusteredOr:
6544 case glslang::EOpSubgroupClusteredXor:
6545 builder.addCapability(spv::CapabilityGroupNonUniform);
6546 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6547 break;
6548 case glslang::EOpSubgroupQuadBroadcast:
6549 case glslang::EOpSubgroupQuadSwapHorizontal:
6550 case glslang::EOpSubgroupQuadSwapVertical:
6551 case glslang::EOpSubgroupQuadSwapDiagonal:
6552 builder.addCapability(spv::CapabilityGroupNonUniform);
6553 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6554 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006555#ifdef NV_EXTENSIONS
6556 case glslang::EOpSubgroupPartitionedAdd:
6557 case glslang::EOpSubgroupPartitionedMul:
6558 case glslang::EOpSubgroupPartitionedMin:
6559 case glslang::EOpSubgroupPartitionedMax:
6560 case glslang::EOpSubgroupPartitionedAnd:
6561 case glslang::EOpSubgroupPartitionedOr:
6562 case glslang::EOpSubgroupPartitionedXor:
6563 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6564 case glslang::EOpSubgroupPartitionedInclusiveMul:
6565 case glslang::EOpSubgroupPartitionedInclusiveMin:
6566 case glslang::EOpSubgroupPartitionedInclusiveMax:
6567 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6568 case glslang::EOpSubgroupPartitionedInclusiveOr:
6569 case glslang::EOpSubgroupPartitionedInclusiveXor:
6570 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6571 case glslang::EOpSubgroupPartitionedExclusiveMul:
6572 case glslang::EOpSubgroupPartitionedExclusiveMin:
6573 case glslang::EOpSubgroupPartitionedExclusiveMax:
6574 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6575 case glslang::EOpSubgroupPartitionedExclusiveOr:
6576 case glslang::EOpSubgroupPartitionedExclusiveXor:
6577 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6578 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6579 break;
6580#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006581 default: assert(0 && "Unhandled subgroup operation!");
6582 }
6583
6584 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6585 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6586 const bool isBool = typeProxy == glslang::EbtBool;
6587
6588 spv::Op opCode = spv::OpNop;
6589
6590 // Figure out which opcode to use.
6591 switch (op) {
6592 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6593 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6594 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6595 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6596 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6597 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6598 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6599 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6600 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6601 case glslang::EOpSubgroupBallotBitCount:
6602 case glslang::EOpSubgroupBallotInclusiveBitCount:
6603 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6604 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6605 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6606 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6607 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6608 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6609 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6610 case glslang::EOpSubgroupAdd:
6611 case glslang::EOpSubgroupInclusiveAdd:
6612 case glslang::EOpSubgroupExclusiveAdd:
6613 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006614#ifdef NV_EXTENSIONS
6615 case glslang::EOpSubgroupPartitionedAdd:
6616 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6617 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6618#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006619 if (isFloat) {
6620 opCode = spv::OpGroupNonUniformFAdd;
6621 } else {
6622 opCode = spv::OpGroupNonUniformIAdd;
6623 }
6624 break;
6625 case glslang::EOpSubgroupMul:
6626 case glslang::EOpSubgroupInclusiveMul:
6627 case glslang::EOpSubgroupExclusiveMul:
6628 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006629#ifdef NV_EXTENSIONS
6630 case glslang::EOpSubgroupPartitionedMul:
6631 case glslang::EOpSubgroupPartitionedInclusiveMul:
6632 case glslang::EOpSubgroupPartitionedExclusiveMul:
6633#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006634 if (isFloat) {
6635 opCode = spv::OpGroupNonUniformFMul;
6636 } else {
6637 opCode = spv::OpGroupNonUniformIMul;
6638 }
6639 break;
6640 case glslang::EOpSubgroupMin:
6641 case glslang::EOpSubgroupInclusiveMin:
6642 case glslang::EOpSubgroupExclusiveMin:
6643 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006644#ifdef NV_EXTENSIONS
6645 case glslang::EOpSubgroupPartitionedMin:
6646 case glslang::EOpSubgroupPartitionedInclusiveMin:
6647 case glslang::EOpSubgroupPartitionedExclusiveMin:
6648#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006649 if (isFloat) {
6650 opCode = spv::OpGroupNonUniformFMin;
6651 } else if (isUnsigned) {
6652 opCode = spv::OpGroupNonUniformUMin;
6653 } else {
6654 opCode = spv::OpGroupNonUniformSMin;
6655 }
6656 break;
6657 case glslang::EOpSubgroupMax:
6658 case glslang::EOpSubgroupInclusiveMax:
6659 case glslang::EOpSubgroupExclusiveMax:
6660 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006661#ifdef NV_EXTENSIONS
6662 case glslang::EOpSubgroupPartitionedMax:
6663 case glslang::EOpSubgroupPartitionedInclusiveMax:
6664 case glslang::EOpSubgroupPartitionedExclusiveMax:
6665#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006666 if (isFloat) {
6667 opCode = spv::OpGroupNonUniformFMax;
6668 } else if (isUnsigned) {
6669 opCode = spv::OpGroupNonUniformUMax;
6670 } else {
6671 opCode = spv::OpGroupNonUniformSMax;
6672 }
6673 break;
6674 case glslang::EOpSubgroupAnd:
6675 case glslang::EOpSubgroupInclusiveAnd:
6676 case glslang::EOpSubgroupExclusiveAnd:
6677 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006678#ifdef NV_EXTENSIONS
6679 case glslang::EOpSubgroupPartitionedAnd:
6680 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6681 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6682#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006683 if (isBool) {
6684 opCode = spv::OpGroupNonUniformLogicalAnd;
6685 } else {
6686 opCode = spv::OpGroupNonUniformBitwiseAnd;
6687 }
6688 break;
6689 case glslang::EOpSubgroupOr:
6690 case glslang::EOpSubgroupInclusiveOr:
6691 case glslang::EOpSubgroupExclusiveOr:
6692 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006693#ifdef NV_EXTENSIONS
6694 case glslang::EOpSubgroupPartitionedOr:
6695 case glslang::EOpSubgroupPartitionedInclusiveOr:
6696 case glslang::EOpSubgroupPartitionedExclusiveOr:
6697#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006698 if (isBool) {
6699 opCode = spv::OpGroupNonUniformLogicalOr;
6700 } else {
6701 opCode = spv::OpGroupNonUniformBitwiseOr;
6702 }
6703 break;
6704 case glslang::EOpSubgroupXor:
6705 case glslang::EOpSubgroupInclusiveXor:
6706 case glslang::EOpSubgroupExclusiveXor:
6707 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006708#ifdef NV_EXTENSIONS
6709 case glslang::EOpSubgroupPartitionedXor:
6710 case glslang::EOpSubgroupPartitionedInclusiveXor:
6711 case glslang::EOpSubgroupPartitionedExclusiveXor:
6712#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006713 if (isBool) {
6714 opCode = spv::OpGroupNonUniformLogicalXor;
6715 } else {
6716 opCode = spv::OpGroupNonUniformBitwiseXor;
6717 }
6718 break;
6719 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6720 case glslang::EOpSubgroupQuadSwapHorizontal:
6721 case glslang::EOpSubgroupQuadSwapVertical:
6722 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6723 default: assert(0 && "Unhandled subgroup operation!");
6724 }
6725
John Kessenich149afc32018-08-14 13:31:43 -06006726 // get the right Group Operation
6727 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006728 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006729 default:
6730 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006731 case glslang::EOpSubgroupBallotBitCount:
6732 case glslang::EOpSubgroupAdd:
6733 case glslang::EOpSubgroupMul:
6734 case glslang::EOpSubgroupMin:
6735 case glslang::EOpSubgroupMax:
6736 case glslang::EOpSubgroupAnd:
6737 case glslang::EOpSubgroupOr:
6738 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006739 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006740 break;
6741 case glslang::EOpSubgroupBallotInclusiveBitCount:
6742 case glslang::EOpSubgroupInclusiveAdd:
6743 case glslang::EOpSubgroupInclusiveMul:
6744 case glslang::EOpSubgroupInclusiveMin:
6745 case glslang::EOpSubgroupInclusiveMax:
6746 case glslang::EOpSubgroupInclusiveAnd:
6747 case glslang::EOpSubgroupInclusiveOr:
6748 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006749 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006750 break;
6751 case glslang::EOpSubgroupBallotExclusiveBitCount:
6752 case glslang::EOpSubgroupExclusiveAdd:
6753 case glslang::EOpSubgroupExclusiveMul:
6754 case glslang::EOpSubgroupExclusiveMin:
6755 case glslang::EOpSubgroupExclusiveMax:
6756 case glslang::EOpSubgroupExclusiveAnd:
6757 case glslang::EOpSubgroupExclusiveOr:
6758 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006759 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006760 break;
6761 case glslang::EOpSubgroupClusteredAdd:
6762 case glslang::EOpSubgroupClusteredMul:
6763 case glslang::EOpSubgroupClusteredMin:
6764 case glslang::EOpSubgroupClusteredMax:
6765 case glslang::EOpSubgroupClusteredAnd:
6766 case glslang::EOpSubgroupClusteredOr:
6767 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006768 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006769 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006770#ifdef NV_EXTENSIONS
6771 case glslang::EOpSubgroupPartitionedAdd:
6772 case glslang::EOpSubgroupPartitionedMul:
6773 case glslang::EOpSubgroupPartitionedMin:
6774 case glslang::EOpSubgroupPartitionedMax:
6775 case glslang::EOpSubgroupPartitionedAnd:
6776 case glslang::EOpSubgroupPartitionedOr:
6777 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006778 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006779 break;
6780 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6781 case glslang::EOpSubgroupPartitionedInclusiveMul:
6782 case glslang::EOpSubgroupPartitionedInclusiveMin:
6783 case glslang::EOpSubgroupPartitionedInclusiveMax:
6784 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6785 case glslang::EOpSubgroupPartitionedInclusiveOr:
6786 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006787 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006788 break;
6789 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6790 case glslang::EOpSubgroupPartitionedExclusiveMul:
6791 case glslang::EOpSubgroupPartitionedExclusiveMin:
6792 case glslang::EOpSubgroupPartitionedExclusiveMax:
6793 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6794 case glslang::EOpSubgroupPartitionedExclusiveOr:
6795 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006796 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006797 break;
6798#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006799 }
6800
John Kessenich149afc32018-08-14 13:31:43 -06006801 // build the instruction
6802 std::vector<spv::IdImmediate> spvGroupOperands;
6803
6804 // Every operation begins with the Execution Scope operand.
6805 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6806 spvGroupOperands.push_back(executionScope);
6807
6808 // Next, for all operations that use a Group Operation, push that as an operand.
6809 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006810 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006811 spvGroupOperands.push_back(groupOperand);
6812 }
6813
John Kessenich66011cb2018-03-06 16:12:04 -07006814 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006815 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6816 spv::IdImmediate operand = { true, *opIt };
6817 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006818 }
6819
6820 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006821 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006822 switch (op) {
6823 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006824 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6825 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6826 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6827 }
6828 if (directionId != spv::NoResult) {
6829 spv::IdImmediate direction = { true, directionId };
6830 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006831 }
6832
6833 return builder.createOp(opCode, typeId, spvGroupOperands);
6834}
6835
John Kessenich5e4b1242015-08-06 22:53:06 -06006836spv::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 -06006837{
John Kessenich66011cb2018-03-06 16:12:04 -07006838 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6839 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006840
John Kessenich140f3df2015-06-26 16:58:36 -06006841 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006842 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006843 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006844 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006845 spv::Id typeId0 = 0;
6846 if (consumedOperands > 0)
6847 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006848 spv::Id typeId1 = 0;
6849 if (consumedOperands > 1)
6850 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006851 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006852
6853 switch (op) {
6854 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006855 if (isFloat)
6856 libCall = spv::GLSLstd450FMin;
6857 else if (isUnsigned)
6858 libCall = spv::GLSLstd450UMin;
6859 else
6860 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006861 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006862 break;
6863 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006864 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006865 break;
6866 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006867 if (isFloat)
6868 libCall = spv::GLSLstd450FMax;
6869 else if (isUnsigned)
6870 libCall = spv::GLSLstd450UMax;
6871 else
6872 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006873 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006874 break;
6875 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006876 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006877 break;
6878 case glslang::EOpDot:
6879 opCode = spv::OpDot;
6880 break;
6881 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006882 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006883 break;
6884
6885 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006886 if (isFloat)
6887 libCall = spv::GLSLstd450FClamp;
6888 else if (isUnsigned)
6889 libCall = spv::GLSLstd450UClamp;
6890 else
6891 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006892 builder.promoteScalar(precision, operands.front(), operands[1]);
6893 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006894 break;
6895 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006896 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6897 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006898 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006899 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006900 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006901 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006902 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006903 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006904 break;
6905 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006906 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006907 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006908 break;
6909 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006910 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006911 builder.promoteScalar(precision, operands[0], operands[2]);
6912 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006913 break;
6914
6915 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006916 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006917 break;
6918 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006919 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006920 break;
6921 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006922 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006923 break;
6924 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006925 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006926 break;
6927 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006928 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006929 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006930 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006931#ifdef AMD_EXTENSIONS
6932 if (typeProxy == glslang::EbtFloat16)
6933 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6934#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006935 libCall = spv::GLSLstd450InterpolateAtSample;
6936 break;
6937 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006938#ifdef AMD_EXTENSIONS
6939 if (typeProxy == glslang::EbtFloat16)
6940 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6941#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006942 libCall = spv::GLSLstd450InterpolateAtOffset;
6943 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006944 case glslang::EOpAddCarry:
6945 opCode = spv::OpIAddCarry;
6946 typeId = builder.makeStructResultType(typeId0, typeId0);
6947 consumedOperands = 2;
6948 break;
6949 case glslang::EOpSubBorrow:
6950 opCode = spv::OpISubBorrow;
6951 typeId = builder.makeStructResultType(typeId0, typeId0);
6952 consumedOperands = 2;
6953 break;
6954 case glslang::EOpUMulExtended:
6955 opCode = spv::OpUMulExtended;
6956 typeId = builder.makeStructResultType(typeId0, typeId0);
6957 consumedOperands = 2;
6958 break;
6959 case glslang::EOpIMulExtended:
6960 opCode = spv::OpSMulExtended;
6961 typeId = builder.makeStructResultType(typeId0, typeId0);
6962 consumedOperands = 2;
6963 break;
6964 case glslang::EOpBitfieldExtract:
6965 if (isUnsigned)
6966 opCode = spv::OpBitFieldUExtract;
6967 else
6968 opCode = spv::OpBitFieldSExtract;
6969 break;
6970 case glslang::EOpBitfieldInsert:
6971 opCode = spv::OpBitFieldInsert;
6972 break;
6973
6974 case glslang::EOpFma:
6975 libCall = spv::GLSLstd450Fma;
6976 break;
6977 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006978 {
6979 libCall = spv::GLSLstd450FrexpStruct;
6980 assert(builder.isPointerType(typeId1));
6981 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006982 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006983#ifdef AMD_EXTENSIONS
6984 if (width == 16)
6985 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6986 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6987#endif
Rex Xu470026f2017-03-29 17:12:40 +08006988 if (builder.getNumComponents(operands[0]) == 1)
6989 frexpIntType = builder.makeIntegerType(width, true);
6990 else
6991 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6992 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6993 consumedOperands = 1;
6994 }
John Kessenich55e7d112015-11-15 21:33:39 -07006995 break;
6996 case glslang::EOpLdexp:
6997 libCall = spv::GLSLstd450Ldexp;
6998 break;
6999
Rex Xu574ab042016-04-14 16:53:07 +08007000 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007001 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007002
John Kessenich66011cb2018-03-06 16:12:04 -07007003 case glslang::EOpSubgroupBroadcast:
7004 case glslang::EOpSubgroupBallotBitExtract:
7005 case glslang::EOpSubgroupShuffle:
7006 case glslang::EOpSubgroupShuffleXor:
7007 case glslang::EOpSubgroupShuffleUp:
7008 case glslang::EOpSubgroupShuffleDown:
7009 case glslang::EOpSubgroupClusteredAdd:
7010 case glslang::EOpSubgroupClusteredMul:
7011 case glslang::EOpSubgroupClusteredMin:
7012 case glslang::EOpSubgroupClusteredMax:
7013 case glslang::EOpSubgroupClusteredAnd:
7014 case glslang::EOpSubgroupClusteredOr:
7015 case glslang::EOpSubgroupClusteredXor:
7016 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007017#ifdef NV_EXTENSIONS
7018 case glslang::EOpSubgroupPartitionedAdd:
7019 case glslang::EOpSubgroupPartitionedMul:
7020 case glslang::EOpSubgroupPartitionedMin:
7021 case glslang::EOpSubgroupPartitionedMax:
7022 case glslang::EOpSubgroupPartitionedAnd:
7023 case glslang::EOpSubgroupPartitionedOr:
7024 case glslang::EOpSubgroupPartitionedXor:
7025 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7026 case glslang::EOpSubgroupPartitionedInclusiveMul:
7027 case glslang::EOpSubgroupPartitionedInclusiveMin:
7028 case glslang::EOpSubgroupPartitionedInclusiveMax:
7029 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7030 case glslang::EOpSubgroupPartitionedInclusiveOr:
7031 case glslang::EOpSubgroupPartitionedInclusiveXor:
7032 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7033 case glslang::EOpSubgroupPartitionedExclusiveMul:
7034 case glslang::EOpSubgroupPartitionedExclusiveMin:
7035 case glslang::EOpSubgroupPartitionedExclusiveMax:
7036 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7037 case glslang::EOpSubgroupPartitionedExclusiveOr:
7038 case glslang::EOpSubgroupPartitionedExclusiveXor:
7039#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007040 return createSubgroupOperation(op, typeId, operands, typeProxy);
7041
Rex Xu9d93a232016-05-05 12:30:44 +08007042#ifdef AMD_EXTENSIONS
7043 case glslang::EOpSwizzleInvocations:
7044 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7045 libCall = spv::SwizzleInvocationsAMD;
7046 break;
7047 case glslang::EOpSwizzleInvocationsMasked:
7048 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7049 libCall = spv::SwizzleInvocationsMaskedAMD;
7050 break;
7051 case glslang::EOpWriteInvocation:
7052 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7053 libCall = spv::WriteInvocationAMD;
7054 break;
7055
7056 case glslang::EOpMin3:
7057 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7058 if (isFloat)
7059 libCall = spv::FMin3AMD;
7060 else {
7061 if (isUnsigned)
7062 libCall = spv::UMin3AMD;
7063 else
7064 libCall = spv::SMin3AMD;
7065 }
7066 break;
7067 case glslang::EOpMax3:
7068 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7069 if (isFloat)
7070 libCall = spv::FMax3AMD;
7071 else {
7072 if (isUnsigned)
7073 libCall = spv::UMax3AMD;
7074 else
7075 libCall = spv::SMax3AMD;
7076 }
7077 break;
7078 case glslang::EOpMid3:
7079 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7080 if (isFloat)
7081 libCall = spv::FMid3AMD;
7082 else {
7083 if (isUnsigned)
7084 libCall = spv::UMid3AMD;
7085 else
7086 libCall = spv::SMid3AMD;
7087 }
7088 break;
7089
7090 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007091 if (typeProxy == glslang::EbtFloat16)
7092 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007093 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7094 libCall = spv::InterpolateAtVertexAMD;
7095 break;
7096#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007097 case glslang::EOpBarrier:
7098 {
7099 // This is for the extended controlBarrier function, with four operands.
7100 // The unextended barrier() goes through createNoArgOperation.
7101 assert(operands.size() == 4);
7102 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7103 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7104 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7105 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7106 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7107 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7108 }
7109 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7110 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7111 }
7112 return 0;
7113 }
7114 break;
7115 case glslang::EOpMemoryBarrier:
7116 {
7117 // This is for the extended memoryBarrier function, with three operands.
7118 // The unextended memoryBarrier() goes through createNoArgOperation.
7119 assert(operands.size() == 3);
7120 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7121 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7122 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7123 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7124 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7125 }
7126 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7127 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7128 }
7129 return 0;
7130 }
7131 break;
Chao Chen3c366992018-09-19 11:41:59 -07007132
7133#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007134 case glslang::EOpReportIntersectionNV:
7135 {
7136 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007137 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007138 }
7139 break;
7140 case glslang::EOpTraceNV:
7141 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007142 builder.createNoResultOp(spv::OpTraceNV, operands);
7143 return 0;
7144 }
7145 break;
7146 case glslang::EOpExecuteCallableNV:
7147 {
7148 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007149 return 0;
7150 }
7151 break;
Chao Chen3c366992018-09-19 11:41:59 -07007152 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7153 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7154 return 0;
7155#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007156 case glslang::EOpCooperativeMatrixMulAdd:
7157 opCode = spv::OpCooperativeMatrixMulAddNV;
7158 break;
7159
John Kessenich140f3df2015-06-26 16:58:36 -06007160 default:
7161 return 0;
7162 }
7163
7164 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007165 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007166 // Use an extended instruction from the standard library.
7167 // Construct the call arguments, without modifying the original operands vector.
7168 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7169 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007170 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007171 } else if (opCode == spv::OpDot && !isFloat) {
7172 // int dot(int, int)
7173 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7174 const int componentCount = builder.getNumComponents(operands[0]);
7175 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7176 builder.setPrecision(mulOp, precision);
7177 id = builder.createCompositeExtract(mulOp, typeId, 0);
7178 for (int i = 1; i < componentCount; ++i) {
7179 builder.setPrecision(id, precision);
7180 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7181 }
John Kessenich2359bd02015-12-06 19:29:11 -07007182 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007183 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007184 case 0:
7185 // should all be handled by visitAggregate and createNoArgOperation
7186 assert(0);
7187 return 0;
7188 case 1:
7189 // should all be handled by createUnaryOperation
7190 assert(0);
7191 return 0;
7192 case 2:
7193 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7194 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007195 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007196 // anything 3 or over doesn't have l-value operands, so all should be consumed
7197 assert(consumedOperands == operands.size());
7198 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007199 break;
7200 }
7201 }
7202
John Kessenich55e7d112015-11-15 21:33:39 -07007203 // Decode the return types that were structures
7204 switch (op) {
7205 case glslang::EOpAddCarry:
7206 case glslang::EOpSubBorrow:
7207 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7208 id = builder.createCompositeExtract(id, typeId0, 0);
7209 break;
7210 case glslang::EOpUMulExtended:
7211 case glslang::EOpIMulExtended:
7212 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7213 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7214 break;
7215 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007216 {
7217 assert(operands.size() == 2);
7218 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7219 // "exp" is floating-point type (from HLSL intrinsic)
7220 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7221 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7222 builder.createStore(member1, operands[1]);
7223 } else
7224 // "exp" is integer type (from GLSL built-in function)
7225 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7226 id = builder.createCompositeExtract(id, typeId0, 0);
7227 }
John Kessenich55e7d112015-11-15 21:33:39 -07007228 break;
7229 default:
7230 break;
7231 }
7232
John Kessenich32cfd492016-02-02 12:37:46 -07007233 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007234}
7235
Rex Xu9d93a232016-05-05 12:30:44 +08007236// Intrinsics with no arguments (or no return value, and no precision).
7237spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007238{
Jeff Bolz36831c92018-09-05 10:11:41 -05007239 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7240 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007241
7242 switch (op) {
7243 case glslang::EOpEmitVertex:
7244 builder.createNoResultOp(spv::OpEmitVertex);
7245 return 0;
7246 case glslang::EOpEndPrimitive:
7247 builder.createNoResultOp(spv::OpEndPrimitive);
7248 return 0;
7249 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007250 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007251 if (glslangIntermediate->usingVulkanMemoryModel()) {
7252 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7253 spv::MemorySemanticsOutputMemoryKHRMask |
7254 spv::MemorySemanticsAcquireReleaseMask);
7255 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7256 } else {
7257 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7258 }
John Kessenich82979362017-12-11 04:02:24 -07007259 } else {
7260 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7261 spv::MemorySemanticsWorkgroupMemoryMask |
7262 spv::MemorySemanticsAcquireReleaseMask);
7263 }
John Kessenich140f3df2015-06-26 16:58:36 -06007264 return 0;
7265 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007266 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7267 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007268 return 0;
7269 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007270 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7271 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007272 return 0;
7273 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007274 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7275 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007276 return 0;
7277 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007278 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7279 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007280 return 0;
7281 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007282 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7283 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007284 return 0;
7285 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007286 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7287 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007288 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007289 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007290 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007291 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007292 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007293 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007294 case glslang::EOpDeviceMemoryBarrier:
7295 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7296 spv::MemorySemanticsImageMemoryMask |
7297 spv::MemorySemanticsAcquireReleaseMask);
7298 return 0;
7299 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7300 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7301 spv::MemorySemanticsImageMemoryMask |
7302 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007303 return 0;
7304 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007305 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7306 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007307 return 0;
7308 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007309 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7310 spv::MemorySemanticsWorkgroupMemoryMask |
7311 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007312 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007313 case glslang::EOpSubgroupBarrier:
7314 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7315 spv::MemorySemanticsAcquireReleaseMask);
7316 return spv::NoResult;
7317 case glslang::EOpSubgroupMemoryBarrier:
7318 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7319 spv::MemorySemanticsAcquireReleaseMask);
7320 return spv::NoResult;
7321 case glslang::EOpSubgroupMemoryBarrierBuffer:
7322 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7323 spv::MemorySemanticsAcquireReleaseMask);
7324 return spv::NoResult;
7325 case glslang::EOpSubgroupMemoryBarrierImage:
7326 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7327 spv::MemorySemanticsAcquireReleaseMask);
7328 return spv::NoResult;
7329 case glslang::EOpSubgroupMemoryBarrierShared:
7330 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7331 spv::MemorySemanticsAcquireReleaseMask);
7332 return spv::NoResult;
7333 case glslang::EOpSubgroupElect: {
7334 std::vector<spv::Id> operands;
7335 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7336 }
Rex Xu9d93a232016-05-05 12:30:44 +08007337#ifdef AMD_EXTENSIONS
7338 case glslang::EOpTime:
7339 {
7340 std::vector<spv::Id> args; // Dummy arguments
7341 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7342 return builder.setPrecision(id, precision);
7343 }
7344#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007345#ifdef NV_EXTENSIONS
7346 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007347 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007348 return 0;
7349 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007350 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007351 return 0;
7352#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007353 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007354 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007355 return 0;
7356 }
7357}
7358
7359spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7360{
John Kessenich2f273362015-07-18 22:34:27 -06007361 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007362 spv::Id id;
7363 if (symbolValues.end() != iter) {
7364 id = iter->second;
7365 return id;
7366 }
7367
7368 // it was not found, create it
7369 id = createSpvVariable(symbol);
7370 symbolValues[symbol->getId()] = id;
7371
Rex Xuc884b4a2016-06-29 15:03:44 +08007372 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007373 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7374 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7375 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007376#ifdef NV_EXTENSIONS
7377 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7378#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007379 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007380 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007381 if (symbol->getQualifier().hasIndex())
7382 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7383 if (symbol->getQualifier().hasComponent())
7384 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007385 // atomic counters use this:
7386 if (symbol->getQualifier().hasOffset())
7387 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007388 }
7389
scygan2c864272016-05-18 18:09:17 +02007390 if (symbol->getQualifier().hasLocation())
7391 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007392 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007393 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007394 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007395 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007396 }
John Kessenich140f3df2015-06-26 16:58:36 -06007397 if (symbol->getQualifier().hasSet())
7398 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007399 else if (IsDescriptorResource(symbol->getType())) {
7400 // default to 0
7401 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7402 }
John Kessenich140f3df2015-06-26 16:58:36 -06007403 if (symbol->getQualifier().hasBinding())
7404 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007405 else if (IsDescriptorResource(symbol->getType())) {
7406 // default to 0
7407 builder.addDecoration(id, spv::DecorationBinding, 0);
7408 }
John Kessenich6c292d32016-02-15 20:58:50 -07007409 if (symbol->getQualifier().hasAttachment())
7410 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007411 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007412 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007413 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007414 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007415 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7416 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7417 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7418 }
7419 if (symbol->getQualifier().hasXfbOffset())
7420 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007421 }
7422
Rex Xu1da878f2016-02-21 20:59:01 +08007423 if (symbol->getType().isImage()) {
7424 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007425 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007426 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007427 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007428 }
7429
John Kessenich140f3df2015-06-26 16:58:36 -06007430 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007431 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007432 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007433 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007434
John Kessenich5611c6d2018-04-05 11:25:02 -06007435 // nonuniform
7436 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7437
John Kessenichecba76f2017-01-06 00:34:48 -07007438#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007439 if (builtIn == spv::BuiltInSampleMask) {
7440 spv::Decoration decoration;
7441 // GL_NV_sample_mask_override_coverage extension
7442 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007443 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007444 else
7445 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007446 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007447 if (decoration != spv::DecorationMax) {
7448 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7449 }
7450 }
chaoc771d89f2017-01-13 01:10:53 -08007451 else if (builtIn == spv::BuiltInLayer) {
7452 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007453 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007454 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007455 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7456 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7457 }
John Kessenichb41bff62017-08-11 13:07:17 -06007458 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007459 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7460 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007461 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7462 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7463 }
7464 }
7465
chaoc6e5acae2016-12-20 13:28:52 -08007466 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007467 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007468 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007469 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7470 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007471 if (symbol->getQualifier().pervertexNV) {
7472 builder.addDecoration(id, spv::DecorationPerVertexNV);
7473 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7474 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7475 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007476#endif
7477
John Kessenich5d610ee2018-03-07 18:05:55 -07007478 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7479 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7480 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7481 symbol->getType().getQualifier().semanticName);
7482 }
7483
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007484 if (symbol->getBasicType() == glslang::EbtReference) {
7485 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7486 }
7487
John Kessenich140f3df2015-06-26 16:58:36 -06007488 return id;
7489}
7490
Chao Chen3c366992018-09-19 11:41:59 -07007491#ifdef NV_EXTENSIONS
7492// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7493void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7494{
7495 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007496 if (qualifier.perPrimitiveNV) {
7497 // Need to add capability/extension for fragment shader.
7498 // Mesh shader already adds this by default.
7499 if (glslangIntermediate->getStage() == EShLangFragment) {
7500 builder.addCapability(spv::CapabilityMeshShadingNV);
7501 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7502 }
Chao Chen3c366992018-09-19 11:41:59 -07007503 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007504 }
Chao Chen3c366992018-09-19 11:41:59 -07007505 if (qualifier.perViewNV)
7506 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7507 if (qualifier.perTaskNV)
7508 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7509 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007510 if (qualifier.perPrimitiveNV) {
7511 // Need to add capability/extension for fragment shader.
7512 // Mesh shader already adds this by default.
7513 if (glslangIntermediate->getStage() == EShLangFragment) {
7514 builder.addCapability(spv::CapabilityMeshShadingNV);
7515 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7516 }
Chao Chen3c366992018-09-19 11:41:59 -07007517 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007518 }
Chao Chen3c366992018-09-19 11:41:59 -07007519 if (qualifier.perViewNV)
7520 builder.addDecoration(id, spv::DecorationPerViewNV);
7521 if (qualifier.perTaskNV)
7522 builder.addDecoration(id, spv::DecorationPerTaskNV);
7523 }
7524}
7525#endif
7526
John Kessenich55e7d112015-11-15 21:33:39 -07007527// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007528// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007529//
7530// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7531//
7532// Recursively walk the nodes. The nodes form a tree whose leaves are
7533// regular constants, which themselves are trees that createSpvConstant()
7534// recursively walks. So, this function walks the "top" of the tree:
7535// - emit specialization constant-building instructions for specConstant
7536// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007537spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007538{
John Kessenich7cc0e282016-03-20 00:46:02 -06007539 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007540
qining4f4bb812016-04-03 23:55:17 -04007541 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007542 if (! node.getQualifier().specConstant) {
7543 // hand off to the non-spec-constant path
7544 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7545 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007546 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007547 nextConst, false);
7548 }
7549
7550 // We now know we have a specialization constant to build
7551
John Kessenichd94c0032016-05-30 19:29:40 -06007552 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007553 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7554 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7555 std::vector<spv::Id> dimConstId;
7556 for (int dim = 0; dim < 3; ++dim) {
7557 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7558 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007559 if (specConst) {
7560 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7561 glslangIntermediate->getLocalSizeSpecId(dim));
7562 }
qining4f4bb812016-04-03 23:55:17 -04007563 }
7564 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7565 }
7566
7567 // An AST node labelled as specialization constant should be a symbol node.
7568 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7569 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007570 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007571 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007572 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7573 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7574 // will set the builder into spec constant op instruction generating mode.
7575 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007576 result = accessChainLoad(sub_tree->getType());
7577 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007578 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007579 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007580 } else {
7581 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007582 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007583 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007584 builder.addName(result, sn->getName().c_str());
7585 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007586 }
qining4f4bb812016-04-03 23:55:17 -04007587
7588 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7589 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007590 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007591 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007592}
7593
John Kessenich140f3df2015-06-26 16:58:36 -06007594// Use 'consts' as the flattened glslang source of scalar constants to recursively
7595// build the aggregate SPIR-V constant.
7596//
7597// If there are not enough elements present in 'consts', 0 will be substituted;
7598// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7599//
qining08408382016-03-21 09:51:37 -04007600spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007601{
7602 // vector of constants for SPIR-V
7603 std::vector<spv::Id> spvConsts;
7604
7605 // Type is used for struct and array constants
7606 spv::Id typeId = convertGlslangToSpvType(glslangType);
7607
7608 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007609 glslang::TType elementType(glslangType, 0);
7610 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007611 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007612 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007613 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007614 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007615 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007616 } else if (glslangType.isCoopMat()) {
7617 glslang::TType componentType(glslangType.getBasicType());
7618 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007619 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007620 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7621 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007622 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007623 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007624 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7625 bool zero = nextConst >= consts.size();
7626 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007627 case glslang::EbtInt8:
7628 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7629 break;
7630 case glslang::EbtUint8:
7631 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7632 break;
7633 case glslang::EbtInt16:
7634 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7635 break;
7636 case glslang::EbtUint16:
7637 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7638 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007639 case glslang::EbtInt:
7640 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7641 break;
7642 case glslang::EbtUint:
7643 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7644 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007645 case glslang::EbtInt64:
7646 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7647 break;
7648 case glslang::EbtUint64:
7649 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7650 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007651 case glslang::EbtFloat:
7652 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7653 break;
7654 case glslang::EbtDouble:
7655 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7656 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007657 case glslang::EbtFloat16:
7658 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7659 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007660 case glslang::EbtBool:
7661 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7662 break;
7663 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007664 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007665 break;
7666 }
7667 ++nextConst;
7668 }
7669 } else {
7670 // we have a non-aggregate (scalar) constant
7671 bool zero = nextConst >= consts.size();
7672 spv::Id scalar = 0;
7673 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007674 case glslang::EbtInt8:
7675 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7676 break;
7677 case glslang::EbtUint8:
7678 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7679 break;
7680 case glslang::EbtInt16:
7681 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7682 break;
7683 case glslang::EbtUint16:
7684 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7685 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007686 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007687 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007688 break;
7689 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007690 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007691 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007692 case glslang::EbtInt64:
7693 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7694 break;
7695 case glslang::EbtUint64:
7696 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7697 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007698 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007699 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007700 break;
7701 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007702 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007703 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007704 case glslang::EbtFloat16:
7705 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7706 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007707 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007708 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007709 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007710 case glslang::EbtReference:
7711 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7712 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7713 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007714 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007715 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007716 break;
7717 }
7718 ++nextConst;
7719 return scalar;
7720 }
7721
7722 return builder.makeCompositeConstant(typeId, spvConsts);
7723}
7724
John Kessenich7c1aa102015-10-15 13:29:11 -06007725// Return true if the node is a constant or symbol whose reading has no
7726// non-trivial observable cost or effect.
7727bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7728{
7729 // don't know what this is
7730 if (node == nullptr)
7731 return false;
7732
7733 // a constant is safe
7734 if (node->getAsConstantUnion() != nullptr)
7735 return true;
7736
7737 // not a symbol means non-trivial
7738 if (node->getAsSymbolNode() == nullptr)
7739 return false;
7740
7741 // a symbol, depends on what's being read
7742 switch (node->getType().getQualifier().storage) {
7743 case glslang::EvqTemporary:
7744 case glslang::EvqGlobal:
7745 case glslang::EvqIn:
7746 case glslang::EvqInOut:
7747 case glslang::EvqConst:
7748 case glslang::EvqConstReadOnly:
7749 case glslang::EvqUniform:
7750 return true;
7751 default:
7752 return false;
7753 }
qining25262b32016-05-06 17:25:16 -04007754}
John Kessenich7c1aa102015-10-15 13:29:11 -06007755
7756// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007757// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007758// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007759// Return true if trivial.
7760bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7761{
7762 if (node == nullptr)
7763 return false;
7764
John Kessenich84cc15f2017-05-24 16:44:47 -06007765 // count non scalars as trivial, as well as anything coming from HLSL
7766 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007767 return true;
7768
John Kessenich7c1aa102015-10-15 13:29:11 -06007769 // symbols and constants are trivial
7770 if (isTrivialLeaf(node))
7771 return true;
7772
7773 // otherwise, it needs to be a simple operation or one or two leaf nodes
7774
7775 // not a simple operation
7776 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7777 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7778 if (binaryNode == nullptr && unaryNode == nullptr)
7779 return false;
7780
7781 // not on leaf nodes
7782 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7783 return false;
7784
7785 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7786 return false;
7787 }
7788
7789 switch (node->getAsOperator()->getOp()) {
7790 case glslang::EOpLogicalNot:
7791 case glslang::EOpConvIntToBool:
7792 case glslang::EOpConvUintToBool:
7793 case glslang::EOpConvFloatToBool:
7794 case glslang::EOpConvDoubleToBool:
7795 case glslang::EOpEqual:
7796 case glslang::EOpNotEqual:
7797 case glslang::EOpLessThan:
7798 case glslang::EOpGreaterThan:
7799 case glslang::EOpLessThanEqual:
7800 case glslang::EOpGreaterThanEqual:
7801 case glslang::EOpIndexDirect:
7802 case glslang::EOpIndexDirectStruct:
7803 case glslang::EOpLogicalXor:
7804 case glslang::EOpAny:
7805 case glslang::EOpAll:
7806 return true;
7807 default:
7808 return false;
7809 }
7810}
7811
7812// Emit short-circuiting code, where 'right' is never evaluated unless
7813// the left side is true (for &&) or false (for ||).
7814spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7815{
7816 spv::Id boolTypeId = builder.makeBoolType();
7817
7818 // emit left operand
7819 builder.clearAccessChain();
7820 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007821 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007822
7823 // Operands to accumulate OpPhi operands
7824 std::vector<spv::Id> phiOperands;
7825 // accumulate left operand's phi information
7826 phiOperands.push_back(leftId);
7827 phiOperands.push_back(builder.getBuildPoint()->getId());
7828
7829 // Make the two kinds of operation symmetric with a "!"
7830 // || => emit "if (! left) result = right"
7831 // && => emit "if ( left) result = right"
7832 //
7833 // TODO: this runtime "not" for || could be avoided by adding functionality
7834 // to 'builder' to have an "else" without an "then"
7835 if (op == glslang::EOpLogicalOr)
7836 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7837
7838 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007839 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007840
7841 // emit right operand as the "then" part of the "if"
7842 builder.clearAccessChain();
7843 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007844 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007845
7846 // accumulate left operand's phi information
7847 phiOperands.push_back(rightId);
7848 phiOperands.push_back(builder.getBuildPoint()->getId());
7849
7850 // finish the "if"
7851 ifBuilder.makeEndIf();
7852
7853 // phi together the two results
7854 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7855}
7856
Frank Henigman541f7bb2018-01-16 00:18:26 -05007857#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007858// Return type Id of the imported set of extended instructions corresponds to the name.
7859// Import this set if it has not been imported yet.
7860spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7861{
7862 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7863 return extBuiltinMap[name];
7864 else {
Rex Xu51596642016-09-21 18:56:12 +08007865 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007866 spv::Id extBuiltins = builder.import(name);
7867 extBuiltinMap[name] = extBuiltins;
7868 return extBuiltins;
7869 }
7870}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007871#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007872
John Kessenich140f3df2015-06-26 16:58:36 -06007873}; // end anonymous namespace
7874
7875namespace glslang {
7876
John Kessenich68d78fd2015-07-12 19:28:10 -06007877void GetSpirvVersion(std::string& version)
7878{
John Kessenich9e55f632015-07-15 10:03:39 -06007879 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007880 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007881 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007882 version = buf;
7883}
7884
John Kessenicha372a3e2017-11-02 22:32:14 -06007885// For low-order part of the generator's magic number. Bump up
7886// when there is a change in the style (e.g., if SSA form changes,
7887// or a different instruction sequence to do something gets used).
7888int GetSpirvGeneratorVersion()
7889{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007890 // return 1; // start
7891 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007892 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007893 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007894 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007895 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7896 // versions 4 and 6 each generate OpArrayLength as it has long been done
7897 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007898}
7899
John Kessenich140f3df2015-06-26 16:58:36 -06007900// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007901void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007902{
7903 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007904 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007905 if (out.fail())
7906 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007907 for (int i = 0; i < (int)spirv.size(); ++i) {
7908 unsigned int word = spirv[i];
7909 out.write((const char*)&word, 4);
7910 }
7911 out.close();
7912}
7913
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007914// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007915void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007916{
7917 std::ofstream out;
7918 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007919 if (out.fail())
7920 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007921 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007922 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007923 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007924 if (varName != nullptr) {
7925 out << "\t #pragma once" << std::endl;
7926 out << "const uint32_t " << varName << "[] = {" << std::endl;
7927 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007928 const int WORDS_PER_LINE = 8;
7929 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7930 out << "\t";
7931 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7932 const unsigned int word = spirv[i + j];
7933 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7934 if (i + j + 1 < (int)spirv.size()) {
7935 out << ",";
7936 }
7937 }
7938 out << std::endl;
7939 }
Flavio15017db2017-02-15 14:29:33 -08007940 if (varName != nullptr) {
7941 out << "};";
7942 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007943 out.close();
7944}
7945
John Kessenich140f3df2015-06-26 16:58:36 -06007946//
7947// Set up the glslang traversal
7948//
John Kessenich4e11b612018-08-30 16:56:59 -06007949void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007950{
Lei Zhang17535f72016-05-04 15:55:59 -04007951 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007952 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007953}
7954
John Kessenich4e11b612018-08-30 16:56:59 -06007955void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007956 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007957{
John Kessenich140f3df2015-06-26 16:58:36 -06007958 TIntermNode* root = intermediate.getTreeRoot();
7959
7960 if (root == 0)
7961 return;
7962
John Kessenich4e11b612018-08-30 16:56:59 -06007963 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007964 if (options == nullptr)
7965 options = &defaultOptions;
7966
John Kessenich4e11b612018-08-30 16:56:59 -06007967 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007968
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007969 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007970 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007971 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007972 it.dumpSpv(spirv);
7973
GregFfb03a552018-03-29 11:49:14 -06007974#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007975 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7976 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007977 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007978 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007979
John Kessenich4e11b612018-08-30 16:56:59 -06007980 if (options->validate)
7981 SpirvToolsValidate(intermediate, spirv, logger);
7982
John Kessenich717c80a2018-08-23 15:17:10 -06007983 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007984 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007985
GregFcd1f1692017-09-21 18:40:22 -06007986#endif
7987
John Kessenich4e11b612018-08-30 16:56:59 -06007988 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007989}
7990
7991}; // end namespace glslang