blob: d25ccd36e2109c9c7fba84c5695e6885e31d3be3 [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 Kessenich0c1e71a2019-01-10 18:23:06 +07002618 // see if OpSelect can handle it
2619 const auto isOpSelectable = [&]() {
2620 if (node->getBasicType() == glslang::EbtVoid)
2621 return false;
2622 // OpSelect can do all other types starting with SPV 1.4
2623 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2624 // pre-1.4, only scalars and vectors can be handled
2625 if ((!node->getType().isScalar() && !node->getType().isVector()))
2626 return false;
2627 }
2628 return true;
2629 };
2630
John Kessenich4bee5312018-02-20 21:29:05 -07002631 // See if it simple and safe, or required, to execute both sides.
2632 // Crucially, side effects must be either semantically required or avoided,
2633 // and there are performance trade-offs.
2634 // Return true if required or a good idea (and safe) to execute both sides,
2635 // false otherwise.
2636 const auto bothSidesPolicy = [&]() -> bool {
2637 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002638 if (node->getTrueBlock() == nullptr ||
2639 node->getFalseBlock() == nullptr)
2640 return false;
2641
John Kessenich4bee5312018-02-20 21:29:05 -07002642 // required? (unless we write additional code to look for side effects
2643 // and make performance trade-offs if none are present)
2644 if (!node->getShortCircuit())
2645 return true;
2646
2647 // if not required to execute both, decide based on performance/practicality...
2648
John Kessenich0c1e71a2019-01-10 18:23:06 +07002649 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002650 return false;
2651
John Kessenich433e9ff2017-01-26 20:31:11 -07002652 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2653 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2654
2655 // return true if a single operand to ? : is okay for OpSelect
2656 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002657 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002658 };
2659
2660 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2661 operandOkay(node->getFalseBlock()->getAsTyped());
2662 };
2663
John Kessenich4bee5312018-02-20 21:29:05 -07002664 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2665 // emit the condition before doing anything with selection
2666 node->getCondition()->traverse(this);
2667 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2668
2669 // Find a way of executing both sides and selecting the right result.
2670 const auto executeBothSides = [&]() -> void {
2671 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002672 node->getTrueBlock()->traverse(this);
2673 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2674 node->getFalseBlock()->traverse(this);
2675 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2676
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002677 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002678
John Kessenich4bee5312018-02-20 21:29:05 -07002679 // done if void
2680 if (node->getBasicType() == glslang::EbtVoid)
2681 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002682
John Kessenich4bee5312018-02-20 21:29:05 -07002683 // emit code to select between trueValue and falseValue
2684
2685 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002686 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002687 // Emit OpSelect for this selection.
2688
2689 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002690 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2691 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002692 condition = builder.smearScalar(spv::NoPrecision, condition,
2693 builder.makeVectorType(builder.makeBoolType(),
2694 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002695 }
John Kessenich4bee5312018-02-20 21:29:05 -07002696
2697 // OpSelect
2698 result = builder.createTriOp(spv::OpSelect,
2699 convertGlslangToSpvType(node->getType()), condition,
2700 trueValue, falseValue);
2701
2702 builder.clearAccessChain();
2703 builder.setAccessChainRValue(result);
2704 } else {
2705 // We need control flow to select the result.
2706 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2707 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2708
2709 // Selection control:
2710 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2711
2712 // make an "if" based on the value created by the condition
2713 spv::Builder::If ifBuilder(condition, control, builder);
2714
2715 // emit the "then" statement
2716 builder.createStore(trueValue, result);
2717 ifBuilder.makeBeginElse();
2718 // emit the "else" statement
2719 builder.createStore(falseValue, result);
2720
2721 // finish off the control flow
2722 ifBuilder.makeEndIf();
2723
2724 builder.clearAccessChain();
2725 builder.setAccessChainLValue(result);
2726 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002727 };
2728
John Kessenich4bee5312018-02-20 21:29:05 -07002729 // Execute the one side needed, as per the condition
2730 const auto executeOneSide = [&]() {
2731 // Always emit control flow.
2732 if (node->getBasicType() != glslang::EbtVoid)
2733 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002734
John Kessenich4bee5312018-02-20 21:29:05 -07002735 // Selection control:
2736 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2737
2738 // make an "if" based on the value created by the condition
2739 spv::Builder::If ifBuilder(condition, control, builder);
2740
2741 // emit the "then" statement
2742 if (node->getTrueBlock() != nullptr) {
2743 node->getTrueBlock()->traverse(this);
2744 if (result != spv::NoResult)
2745 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2746 }
2747
2748 if (node->getFalseBlock() != nullptr) {
2749 ifBuilder.makeBeginElse();
2750 // emit the "else" statement
2751 node->getFalseBlock()->traverse(this);
2752 if (result != spv::NoResult)
2753 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2754 }
2755
2756 // finish off the control flow
2757 ifBuilder.makeEndIf();
2758
2759 if (result != spv::NoResult) {
2760 builder.clearAccessChain();
2761 builder.setAccessChainLValue(result);
2762 }
2763 };
2764
2765 // Try for OpSelect (or a requirement to execute both sides)
2766 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002767 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2768 if (node->getType().getQualifier().isSpecConstant())
2769 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002770 executeBothSides();
2771 } else
2772 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002773
2774 return false;
2775}
2776
2777bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2778{
2779 // emit and get the condition before doing anything with switch
2780 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002781 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002782
Rex Xu57e65922017-07-04 23:23:40 +08002783 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002784 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002785
John Kessenich140f3df2015-06-26 16:58:36 -06002786 // browse the children to sort out code segments
2787 int defaultSegment = -1;
2788 std::vector<TIntermNode*> codeSegments;
2789 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2790 std::vector<int> caseValues;
2791 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2792 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2793 TIntermNode* child = *c;
2794 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002795 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002796 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002797 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002798 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2799 } else
2800 codeSegments.push_back(child);
2801 }
2802
qining25262b32016-05-06 17:25:16 -04002803 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002804 // statements between the last case and the end of the switch statement
2805 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2806 (int)codeSegments.size() == defaultSegment)
2807 codeSegments.push_back(nullptr);
2808
2809 // make the switch statement
2810 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002811 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002812
2813 // emit all the code in the segments
2814 breakForLoop.push(false);
2815 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2816 builder.nextSwitchSegment(segmentBlocks, s);
2817 if (codeSegments[s])
2818 codeSegments[s]->traverse(this);
2819 else
2820 builder.addSwitchBreak();
2821 }
2822 breakForLoop.pop();
2823
2824 builder.endSwitch(segmentBlocks);
2825
2826 return false;
2827}
2828
2829void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2830{
2831 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002832 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002833
2834 builder.clearAccessChain();
2835 builder.setAccessChainRValue(constant);
2836}
2837
2838bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2839{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002840 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002841 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002842
2843 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002844 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2845 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002846
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002847 // Spec requires back edges to target header blocks, and every header block
2848 // must dominate its merge block. Make a header block first to ensure these
2849 // conditions are met. By definition, it will contain OpLoopMerge, followed
2850 // by a block-ending branch. But we don't want to put any other body/test
2851 // instructions in it, since the body/test may have arbitrary instructions,
2852 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002853 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002854 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002855 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002856 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002857 spv::Block& test = builder.makeNewBlock();
2858 builder.createBranch(&test);
2859
2860 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002861 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002862 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002863 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2864
2865 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002866 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002867 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002868 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002869 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002870 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002871
2872 builder.setBuildPoint(&blocks.continue_target);
2873 if (node->getTerminal())
2874 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002875 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002876 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002877 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002878 builder.createBranch(&blocks.body);
2879
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002880 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002881 builder.setBuildPoint(&blocks.body);
2882 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002883 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002884 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002885 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002886
2887 builder.setBuildPoint(&blocks.continue_target);
2888 if (node->getTerminal())
2889 node->getTerminal()->traverse(this);
2890 if (node->getTest()) {
2891 node->getTest()->traverse(this);
2892 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002893 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002894 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002895 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002896 // TODO: unless there was a break/return/discard instruction
2897 // somewhere in the body, this is an infinite loop, so we should
2898 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002899 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002900 }
John Kessenich140f3df2015-06-26 16:58:36 -06002901 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002902 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002903 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002904 return false;
2905}
2906
2907bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2908{
2909 if (node->getExpression())
2910 node->getExpression()->traverse(this);
2911
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002912 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002913
John Kessenich140f3df2015-06-26 16:58:36 -06002914 switch (node->getFlowOp()) {
2915 case glslang::EOpKill:
2916 builder.makeDiscard();
2917 break;
2918 case glslang::EOpBreak:
2919 if (breakForLoop.top())
2920 builder.createLoopExit();
2921 else
2922 builder.addSwitchBreak();
2923 break;
2924 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002925 builder.createLoopContinue();
2926 break;
2927 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002928 if (node->getExpression()) {
2929 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2930 spv::Id returnId = accessChainLoad(glslangReturnType);
2931 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2932 builder.clearAccessChain();
2933 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2934 builder.setAccessChainLValue(copyId);
2935 multiTypeStore(glslangReturnType, returnId);
2936 returnId = builder.createLoad(copyId);
2937 }
2938 builder.makeReturn(false, returnId);
2939 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002940 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002941
2942 builder.clearAccessChain();
2943 break;
2944
2945 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002946 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002947 break;
2948 }
2949
2950 return false;
2951}
2952
2953spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2954{
qining25262b32016-05-06 17:25:16 -04002955 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002956 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002957 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002958 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002959 spv::Id result = createSpvConstant(*node);
2960 if (result != spv::NoResult)
2961 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002962 }
2963
2964 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002965 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002966 spv::Id spvType = convertGlslangToSpvType(node->getType());
2967
Rex Xucabbb782017-03-24 13:41:14 +08002968 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2969 node->getType().containsBasicType(glslang::EbtInt16) ||
2970 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002971 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002972 switch (storageClass) {
2973 case spv::StorageClassInput:
2974 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002975 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002976 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002977 break;
2978 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002979 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002980 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002981 break;
2982 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002983 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002984 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2985 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002986 else
2987 builder.addCapability(spv::CapabilityStorageUniform16);
2988 break;
2989 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002990 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002991 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2992 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2993 break;
2994 default:
2995 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002996 }
2997 }
Rex Xuf89ad982017-04-07 23:22:33 +08002998
John Kessenich312dcfb2018-07-03 13:19:51 -06002999 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3000 node->getType().containsBasicType(glslang::EbtUint8);
3001 if (contains8BitType) {
3002 if (storageClass == spv::StorageClassPushConstant) {
3003 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3004 builder.addCapability(spv::CapabilityStoragePushConstant8);
3005 } else if (storageClass == spv::StorageClassUniform) {
3006 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3007 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003008 } else if (storageClass == spv::StorageClassStorageBuffer) {
3009 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3010 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003011 }
3012 }
3013
John Kessenich140f3df2015-06-26 16:58:36 -06003014 const char* name = node->getName().c_str();
3015 if (glslang::IsAnonymous(name))
3016 name = "";
3017
3018 return builder.createVariable(storageClass, spvType, name);
3019}
3020
3021// Return type Id of the sampled type.
3022spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3023{
3024 switch (sampler.type) {
3025 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003026#ifdef AMD_EXTENSIONS
3027 case glslang::EbtFloat16:
3028 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3029 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3030 return builder.makeFloatType(16);
3031#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003032 case glslang::EbtInt: return builder.makeIntType(32);
3033 case glslang::EbtUint: return builder.makeUintType(32);
3034 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003035 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003036 return builder.makeFloatType(32);
3037 }
3038}
3039
John Kessenich8c8505c2016-07-26 12:50:38 -06003040// If node is a swizzle operation, return the type that should be used if
3041// the swizzle base is first consumed by another operation, before the swizzle
3042// is applied.
3043spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3044{
John Kessenichecba76f2017-01-06 00:34:48 -07003045 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003046 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3047 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3048 else
3049 return spv::NoType;
3050}
3051
3052// When inverting a swizzle with a parent op, this function
3053// will apply the swizzle operation to a completed parent operation.
3054spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3055{
3056 std::vector<unsigned> swizzle;
3057 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3058 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3059}
3060
John Kessenich8c8505c2016-07-26 12:50:38 -06003061// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3062void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3063{
3064 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3065 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3066 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3067}
3068
John Kessenich3ac051e2015-12-20 11:29:16 -07003069// Convert from a glslang type to an SPV type, by calling into a
3070// recursive version of this function. This establishes the inherited
3071// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003072spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003073{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003074 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003075}
3076
3077// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003078// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003079// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003080spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003081 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3082 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003083{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003084 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003085
3086 switch (type.getBasicType()) {
3087 case glslang::EbtVoid:
3088 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003089 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EbtFloat:
3092 spvType = builder.makeFloatType(32);
3093 break;
3094 case glslang::EbtDouble:
3095 spvType = builder.makeFloatType(64);
3096 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003097 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003098 spvType = builder.makeFloatType(16);
3099 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003100 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003101 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3102 // a 32-bit int where non-0 means true.
3103 if (explicitLayout != glslang::ElpNone)
3104 spvType = builder.makeUintType(32);
3105 else
3106 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003107 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003108 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003109 spvType = builder.makeIntType(8);
3110 break;
3111 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003112 spvType = builder.makeUintType(8);
3113 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003114 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003115 spvType = builder.makeIntType(16);
3116 break;
3117 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003118 spvType = builder.makeUintType(16);
3119 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 case glslang::EbtInt:
3121 spvType = builder.makeIntType(32);
3122 break;
3123 case glslang::EbtUint:
3124 spvType = builder.makeUintType(32);
3125 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003126 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003127 spvType = builder.makeIntType(64);
3128 break;
3129 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003130 spvType = builder.makeUintType(64);
3131 break;
John Kessenich426394d2015-07-23 10:22:48 -06003132 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003133 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003134 spvType = builder.makeUintType(32);
3135 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003136#ifdef NV_EXTENSIONS
3137 case glslang::EbtAccStructNV:
3138 spvType = builder.makeAccelerationStructureNVType();
3139 break;
3140#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003141 case glslang::EbtSampler:
3142 {
3143 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003144 if (sampler.sampler) {
3145 // pure sampler
3146 spvType = builder.makeSamplerType();
3147 } else {
3148 // an image is present, make its type
3149 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3150 sampler.image ? 2 : 1, TranslateImageFormat(type));
3151 if (sampler.combined) {
3152 // already has both image and sampler, make the combined type
3153 spvType = builder.makeSampledImageType(spvType);
3154 }
John Kessenich55e7d112015-11-15 21:33:39 -07003155 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003156 }
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 case glslang::EbtStruct:
3159 case glslang::EbtBlock:
3160 {
3161 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003162 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003163
3164 // Try to share structs for different layouts, but not yet for other
3165 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003166 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003167 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003168 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170
3171 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003172 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003173 memberRemapper[glslangMembers].resize(glslangMembers->size());
3174 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003175 }
3176 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003177 case glslang::EbtReference:
3178 {
3179 // Make the forward pointer, then recurse to convert the structure type, then
3180 // patch up the forward pointer with a real pointer type.
3181 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3182 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3183 forwardPointers[type.getReferentType()] = forwardId;
3184 }
3185 spvType = forwardPointers[type.getReferentType()];
3186 if (!forwardReferenceOnly) {
3187 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3188 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3189 forwardPointers[type.getReferentType()],
3190 referentType);
3191 }
3192 }
3193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003195 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197 }
3198
3199 if (type.isMatrix())
3200 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3201 else {
3202 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3203 if (type.getVectorSize() > 1)
3204 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3205 }
3206
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003207 if (type.isCoopMat()) {
3208 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3209 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3210 if (type.getBasicType() == glslang::EbtFloat16)
3211 builder.addCapability(spv::CapabilityFloat16);
3212
3213 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3214 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3215 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3216
3217 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3218 }
3219
John Kessenich140f3df2015-06-26 16:58:36 -06003220 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003221 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3222
John Kessenichc9a80832015-09-12 12:17:44 -06003223 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003224 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003225 // We need to decorate array strides for types needing explicit layout, except blocks.
3226 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003227 // Use a dummy glslang type for querying internal strides of
3228 // arrays of arrays, but using just a one-dimensional array.
3229 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003230 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3231 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003232
3233 // Will compute the higher-order strides here, rather than making a whole
3234 // pile of types and doing repetitive recursion on their contents.
3235 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3236 }
John Kessenichf8842e52016-01-04 19:22:56 -07003237
3238 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003239 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003240 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003241 if (stride > 0)
3242 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003243 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003244 }
3245 } else {
3246 // single-dimensional array, and don't yet have stride
3247
John Kessenichf8842e52016-01-04 19:22:56 -07003248 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003249 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3250 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003251 }
John Kessenich31ed4832015-09-09 17:51:38 -06003252
John Kessenichead86222018-03-28 18:01:20 -06003253 // Do the outer dimension, which might not be known for a runtime-sized array.
3254 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3255 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003256 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003257 else {
3258 if (!lastBufferBlockMember) {
3259 builder.addExtension("SPV_EXT_descriptor_indexing");
3260 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3261 }
John Kessenichead86222018-03-28 18:01:20 -06003262 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003263 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003264 if (stride > 0)
3265 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003266 }
3267
3268 return spvType;
3269}
3270
John Kessenich0e737842017-03-24 18:38:16 -06003271// TODO: this functionality should exist at a higher level, in creating the AST
3272//
3273// Identify interface members that don't have their required extension turned on.
3274//
3275bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3276{
Chao Chen3c366992018-09-19 11:41:59 -07003277#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003278 auto& extensions = glslangIntermediate->getRequestedExtensions();
3279
Rex Xubcf291a2017-03-29 23:01:36 +08003280 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3281 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3282 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003283 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3284 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3285 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003286
3287 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3288 if (member.getFieldName() == "gl_ViewportMask" &&
3289 extensions.find("GL_NV_viewport_array2") == extensions.end())
3290 return true;
3291 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3292 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3293 return true;
3294 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3295 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3296 return true;
3297 }
3298#endif
John Kessenich0e737842017-03-24 18:38:16 -06003299
3300 return false;
3301};
3302
John Kessenich6090df02016-06-30 21:18:02 -06003303// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3304// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3305// Mutually recursive with convertGlslangToSpvType().
3306spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3307 const glslang::TTypeList* glslangMembers,
3308 glslang::TLayoutPacking explicitLayout,
3309 const glslang::TQualifier& qualifier)
3310{
3311 // Create a vector of struct types for SPIR-V to consume
3312 std::vector<spv::Id> spvMembers;
3313 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 -06003314 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003315 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3316 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3317 if (glslangMember.hiddenMember()) {
3318 ++memberDelta;
3319 if (type.getBasicType() == glslang::EbtBlock)
3320 memberRemapper[glslangMembers][i] = -1;
3321 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003322 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003323 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003324 if (filterMember(glslangMember))
3325 continue;
3326 }
John Kessenich6090df02016-06-30 21:18:02 -06003327 // modify just this child's view of the qualifier
3328 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3329 InheritQualifiers(memberQualifier, qualifier);
3330
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003331 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003332 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003333 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003334
3335 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003336 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3337 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003338
3339 // Make forward pointers for any pointer members, and create a list of members to
3340 // convert to spirv types after creating the struct.
3341 if (glslangMember.getBasicType() == glslang::EbtReference) {
3342 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3343 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3344 }
3345 spvMembers.push_back(
3346 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3347 } else {
3348 spvMembers.push_back(
3349 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3350 }
John Kessenich6090df02016-06-30 21:18:02 -06003351 }
3352 }
3353
3354 // Make the SPIR-V type
3355 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003356 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003357 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3358
3359 // Decorate it
3360 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3361
John Kessenichd72f4882019-01-16 14:55:37 +07003362 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003363 auto it = deferredForwardPointers[i];
3364 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3365 }
3366
John Kessenich6090df02016-06-30 21:18:02 -06003367 return spvType;
3368}
3369
3370void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3371 const glslang::TTypeList* glslangMembers,
3372 glslang::TLayoutPacking explicitLayout,
3373 const glslang::TQualifier& qualifier,
3374 spv::Id spvType)
3375{
3376 // Name and decorate the non-hidden members
3377 int offset = -1;
3378 int locationOffset = 0; // for use within the members of this struct
3379 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3380 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3381 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003382 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003383 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003384 if (filterMember(glslangMember))
3385 continue;
3386 }
John Kessenich6090df02016-06-30 21:18:02 -06003387
3388 // modify just this child's view of the qualifier
3389 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3390 InheritQualifiers(memberQualifier, qualifier);
3391
3392 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003393 if (member < 0)
3394 continue;
3395
3396 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3397 builder.addMemberDecoration(spvType, member,
3398 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3399 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3400 // Add interpolation and auxiliary storage decorations only to
3401 // top-level members of Input and Output storage classes
3402 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3403 type.getQualifier().storage == glslang::EvqVaryingOut) {
3404 if (type.getBasicType() == glslang::EbtBlock ||
3405 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3406 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3407 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003408#ifdef NV_EXTENSIONS
3409 addMeshNVDecoration(spvType, member, memberQualifier);
3410#endif
John Kessenich6090df02016-06-30 21:18:02 -06003411 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003412 }
3413 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003414
John Kessenich5d610ee2018-03-07 18:05:55 -07003415 if (type.getBasicType() == glslang::EbtBlock &&
3416 qualifier.storage == glslang::EvqBuffer) {
3417 // Add memory decorations only to top-level members of shader storage block
3418 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003419 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003420 for (unsigned int i = 0; i < memory.size(); ++i)
3421 builder.addMemberDecoration(spvType, member, memory[i]);
3422 }
John Kessenich6090df02016-06-30 21:18:02 -06003423
John Kessenich5d610ee2018-03-07 18:05:55 -07003424 // Location assignment was already completed correctly by the front end,
3425 // just track whether a member needs to be decorated.
3426 // Ignore member locations if the container is an array, as that's
3427 // ill-specified and decisions have been made to not allow this.
3428 if (! type.isArray() && memberQualifier.hasLocation())
3429 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003430
John Kessenich5d610ee2018-03-07 18:05:55 -07003431 if (qualifier.hasLocation()) // track for upcoming inheritance
3432 locationOffset += glslangIntermediate->computeTypeLocationSize(
3433 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003434
John Kessenich5d610ee2018-03-07 18:05:55 -07003435 // component, XFB, others
3436 if (glslangMember.getQualifier().hasComponent())
3437 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3438 glslangMember.getQualifier().layoutComponent);
3439 if (glslangMember.getQualifier().hasXfbOffset())
3440 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3441 glslangMember.getQualifier().layoutXfbOffset);
3442 else if (explicitLayout != glslang::ElpNone) {
3443 // figure out what to do with offset, which is accumulating
3444 int nextOffset;
3445 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3446 if (offset >= 0)
3447 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3448 offset = nextOffset;
3449 }
John Kessenich6090df02016-06-30 21:18:02 -06003450
John Kessenich5d610ee2018-03-07 18:05:55 -07003451 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3452 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3453 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003454
John Kessenich5d610ee2018-03-07 18:05:55 -07003455 // built-in variable decorations
3456 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3457 if (builtIn != spv::BuiltInMax)
3458 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003459
John Kessenich5611c6d2018-04-05 11:25:02 -06003460 // nonuniform
3461 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3462
John Kessenichead86222018-03-28 18:01:20 -06003463 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3464 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3465 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3466 memberQualifier.semanticName);
3467 }
3468
chaoc771d89f2017-01-13 01:10:53 -08003469#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003470 if (builtIn == spv::BuiltInLayer) {
3471 // SPV_NV_viewport_array2 extension
3472 if (glslangMember.getQualifier().layoutViewportRelative){
3473 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3474 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3475 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003476 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003477 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3478 builder.addMemberDecoration(spvType, member,
3479 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3480 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3481 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3482 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003483 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003484 }
3485 if (glslangMember.getQualifier().layoutPassthrough) {
3486 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3487 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3488 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3489 }
chaoc771d89f2017-01-13 01:10:53 -08003490#endif
John Kessenich6090df02016-06-30 21:18:02 -06003491 }
3492
3493 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003494 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3495 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003496}
3497
John Kessenich6c292d32016-02-15 20:58:50 -07003498// Turn the expression forming the array size into an id.
3499// This is not quite trivial, because of specialization constants.
3500// Sometimes, a raw constant is turned into an Id, and sometimes
3501// a specialization constant expression is.
3502spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3503{
3504 // First, see if this is sized with a node, meaning a specialization constant:
3505 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3506 if (specNode != nullptr) {
3507 builder.clearAccessChain();
3508 specNode->traverse(this);
3509 return accessChainLoad(specNode->getAsTyped()->getType());
3510 }
qining25262b32016-05-06 17:25:16 -04003511
John Kessenich6c292d32016-02-15 20:58:50 -07003512 // Otherwise, need a compile-time (front end) size, get it:
3513 int size = arraySizes.getDimSize(dim);
3514 assert(size > 0);
3515 return builder.makeUintConstant(size);
3516}
3517
John Kessenich103bef92016-02-08 21:38:15 -07003518// Wrap the builder's accessChainLoad to:
3519// - localize handling of RelaxedPrecision
3520// - use the SPIR-V inferred type instead of another conversion of the glslang type
3521// (avoids unnecessary work and possible type punning for structures)
3522// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003523spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3524{
John Kessenich103bef92016-02-08 21:38:15 -07003525 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003526
3527 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3528 coherentFlags |= TranslateCoherent(type);
3529
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003530 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003531 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003532
John Kessenich5611c6d2018-04-05 11:25:02 -06003533 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003534 TranslateNonUniformDecoration(type.getQualifier()),
3535 nominalTypeId,
3536 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003537 TranslateMemoryScope(coherentFlags),
3538 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003539
3540 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003541 if (type.getBasicType() == glslang::EbtBool) {
3542 if (builder.isScalarType(nominalTypeId)) {
3543 // Conversion for bool
3544 spv::Id boolType = builder.makeBoolType();
3545 if (nominalTypeId != boolType)
3546 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3547 } else if (builder.isVectorType(nominalTypeId)) {
3548 // Conversion for bvec
3549 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3550 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3551 if (nominalTypeId != bvecType)
3552 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3553 }
3554 }
John Kessenich103bef92016-02-08 21:38:15 -07003555
3556 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003557}
3558
Rex Xu27253232016-02-23 17:51:09 +08003559// Wrap the builder's accessChainStore to:
3560// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003561//
3562// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003563void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3564{
3565 // Need to convert to abstract types when necessary
3566 if (type.getBasicType() == glslang::EbtBool) {
3567 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3568
3569 if (builder.isScalarType(nominalTypeId)) {
3570 // Conversion for bool
3571 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003572 if (nominalTypeId != boolType) {
3573 // keep these outside arguments, for determinant order-of-evaluation
3574 spv::Id one = builder.makeUintConstant(1);
3575 spv::Id zero = builder.makeUintConstant(0);
3576 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3577 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003578 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003579 } else if (builder.isVectorType(nominalTypeId)) {
3580 // Conversion for bvec
3581 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3582 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003583 if (nominalTypeId != bvecType) {
3584 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003585 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3586 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3587 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003588 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003589 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3590 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003591 }
3592 }
3593
Jeff Bolz36831c92018-09-05 10:11:41 -05003594 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3595 coherentFlags |= TranslateCoherent(type);
3596
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003597 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003598 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003599
Jeff Bolz36831c92018-09-05 10:11:41 -05003600 builder.accessChainStore(rvalue,
3601 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003602 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003603}
3604
John Kessenich4bf71552016-09-02 11:20:21 -06003605// For storing when types match at the glslang level, but not might match at the
3606// SPIR-V level.
3607//
3608// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003609// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003610// as in a member-decorated way.
3611//
3612// NOTE: This function can handle any store request; if it's not special it
3613// simplifies to a simple OpStore.
3614//
3615// Implicitly uses the existing builder.accessChain as the storage target.
3616void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3617{
John Kessenichb3e24e42016-09-11 12:33:43 -06003618 // we only do the complex path here if it's an aggregate
3619 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003620 accessChainStore(type, rValue);
3621 return;
3622 }
3623
John Kessenichb3e24e42016-09-11 12:33:43 -06003624 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003625 spv::Id rType = builder.getTypeId(rValue);
3626 spv::Id lValue = builder.accessChainGetLValue();
3627 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3628 if (lType == rType) {
3629 accessChainStore(type, rValue);
3630 return;
3631 }
3632
John Kessenichb3e24e42016-09-11 12:33:43 -06003633 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003634 // where the two types were the same type in GLSL. This requires member
3635 // by member copy, recursively.
3636
John Kessenichb3e24e42016-09-11 12:33:43 -06003637 // If an array, copy element by element.
3638 if (type.isArray()) {
3639 glslang::TType glslangElementType(type, 0);
3640 spv::Id elementRType = builder.getContainedTypeId(rType);
3641 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3642 // get the source member
3643 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003644
John Kessenichb3e24e42016-09-11 12:33:43 -06003645 // set up the target storage
3646 builder.clearAccessChain();
3647 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003648 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003649
John Kessenichb3e24e42016-09-11 12:33:43 -06003650 // store the member
3651 multiTypeStore(glslangElementType, elementRValue);
3652 }
3653 } else {
3654 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003655
John Kessenichb3e24e42016-09-11 12:33:43 -06003656 // loop over structure members
3657 const glslang::TTypeList& members = *type.getStruct();
3658 for (int m = 0; m < (int)members.size(); ++m) {
3659 const glslang::TType& glslangMemberType = *members[m].type;
3660
3661 // get the source member
3662 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3663 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3664
3665 // set up the target storage
3666 builder.clearAccessChain();
3667 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003668 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003669
3670 // store the member
3671 multiTypeStore(glslangMemberType, memberRValue);
3672 }
John Kessenich4bf71552016-09-02 11:20:21 -06003673 }
3674}
3675
John Kessenichf85e8062015-12-19 13:57:10 -07003676// Decide whether or not this type should be
3677// decorated with offsets and strides, and if so
3678// whether std140 or std430 rules should be applied.
3679glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003680{
John Kessenichf85e8062015-12-19 13:57:10 -07003681 // has to be a block
3682 if (type.getBasicType() != glslang::EbtBlock)
3683 return glslang::ElpNone;
3684
Chao Chen3c366992018-09-19 11:41:59 -07003685 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003686 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003687 type.getQualifier().storage != glslang::EvqBuffer &&
3688 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003689 return glslang::ElpNone;
3690
3691 // return the layout to use
3692 switch (type.getQualifier().layoutPacking) {
3693 case glslang::ElpStd140:
3694 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003695 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003696 return type.getQualifier().layoutPacking;
3697 default:
3698 return glslang::ElpNone;
3699 }
John Kessenich31ed4832015-09-09 17:51:38 -06003700}
3701
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003702// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003703int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003704{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003705 int size;
John Kessenich49987892015-12-29 17:11:44 -07003706 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003707 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003708
3709 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003710}
3711
John Kessenich49987892015-12-29 17:11:44 -07003712// 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 -07003713// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003714int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003715{
John Kessenich49987892015-12-29 17:11:44 -07003716 glslang::TType elementType;
3717 elementType.shallowCopy(matrixType);
3718 elementType.clearArraySizes();
3719
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003720 int size;
John Kessenich49987892015-12-29 17:11:44 -07003721 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003722 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003723
3724 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003725}
3726
John Kessenich5e4b1242015-08-06 22:53:06 -06003727// Given a member type of a struct, realign the current offset for it, and compute
3728// the next (not yet aligned) offset for the next member, which will get aligned
3729// on the next call.
3730// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3731// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3732// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003733void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003734 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003735{
3736 // this will get a positive value when deemed necessary
3737 nextOffset = -1;
3738
John Kessenich5e4b1242015-08-06 22:53:06 -06003739 // override anything in currentOffset with user-set offset
3740 if (memberType.getQualifier().hasOffset())
3741 currentOffset = memberType.getQualifier().layoutOffset;
3742
3743 // It could be that current linker usage in glslang updated all the layoutOffset,
3744 // in which case the following code does not matter. But, that's not quite right
3745 // once cross-compilation unit GLSL validation is done, as the original user
3746 // settings are needed in layoutOffset, and then the following will come into play.
3747
John Kessenichf85e8062015-12-19 13:57:10 -07003748 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 if (! memberType.getQualifier().hasOffset())
3750 currentOffset = -1;
3751
3752 return;
3753 }
3754
John Kessenichf85e8062015-12-19 13:57:10 -07003755 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003756 if (currentOffset < 0)
3757 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003758
John Kessenich5e4b1242015-08-06 22:53:06 -06003759 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3760 // but possibly not yet correctly aligned.
3761
3762 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003763 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003764 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003765
3766 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003767 // TODO: make this consistent in early phases of code:
3768 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3769 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3770 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003771 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003772 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003773 int dummySize;
3774 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3775 if (componentAlignment <= 4)
3776 memberAlignment = componentAlignment;
3777 }
3778
3779 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003781
3782 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003783 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003784 glslang::RoundToPow2(currentOffset, 16);
3785
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 nextOffset = currentOffset + memberSize;
3787}
3788
David Netoa901ffe2016-06-08 14:11:40 +01003789void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003790{
David Netoa901ffe2016-06-08 14:11:40 +01003791 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3792 switch (glslangBuiltIn)
3793 {
3794 case glslang::EbvClipDistance:
3795 case glslang::EbvCullDistance:
3796 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003797#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003798 case glslang::EbvViewportMaskNV:
3799 case glslang::EbvSecondaryPositionNV:
3800 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003801 case glslang::EbvPositionPerViewNV:
3802 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003803 case glslang::EbvTaskCountNV:
3804 case glslang::EbvPrimitiveCountNV:
3805 case glslang::EbvPrimitiveIndicesNV:
3806 case glslang::EbvClipDistancePerViewNV:
3807 case glslang::EbvCullDistancePerViewNV:
3808 case glslang::EbvLayerPerViewNV:
3809 case glslang::EbvMeshViewCountNV:
3810 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003811#endif
David Netoa901ffe2016-06-08 14:11:40 +01003812 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3813 // Alternately, we could just call this for any glslang built-in, since the
3814 // capability already guards against duplicates.
3815 TranslateBuiltInDecoration(glslangBuiltIn, false);
3816 break;
3817 default:
3818 // Capabilities were already generated when the struct was declared.
3819 break;
3820 }
John Kessenichebb50532016-05-16 19:22:05 -06003821}
3822
John Kessenich6fccb3c2016-09-19 16:01:41 -06003823bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003824{
John Kessenicheee9d532016-09-19 18:09:30 -06003825 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003826}
3827
John Kessenichd41993d2017-09-10 15:21:05 -06003828// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003829// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3830// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003831bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003832{
John Kessenich6a14f782017-12-04 02:48:10 -07003833 assert(qualifier == glslang::EvqIn ||
3834 qualifier == glslang::EvqOut ||
3835 qualifier == glslang::EvqInOut ||
3836 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003837 return qualifier != glslang::EvqConstReadOnly;
3838}
3839
3840// Is parameter pass-by-original?
3841bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3842 bool implicitThisParam)
3843{
3844 if (implicitThisParam) // implicit this
3845 return true;
3846 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003847 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003848 return paramType.containsOpaque() || // sampler, etc.
3849 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3850}
3851
John Kessenich140f3df2015-06-26 16:58:36 -06003852// Make all the functions, skeletally, without actually visiting their bodies.
3853void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3854{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003855 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003856 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3857 if (paramPrecision != spv::NoPrecision)
3858 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003859 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003860 if (type.getBasicType() == glslang::EbtReference) {
3861 // Original and non-writable params pass the pointer directly and
3862 // use restrict/aliased, others are stored to a pointer in Function
3863 // memory and use RestrictPointer/AliasedPointer.
3864 if (originalParam(type.getQualifier().storage, type, false) ||
3865 !writableParam(type.getQualifier().storage)) {
3866 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3867 } else {
3868 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3869 }
3870 }
John Kessenichfad62972017-07-18 02:35:46 -06003871 };
3872
John Kessenich140f3df2015-06-26 16:58:36 -06003873 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3874 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003875 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003876 continue;
3877
3878 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003879 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003880 //
qining25262b32016-05-06 17:25:16 -04003881 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003882 // function. What it is an address of varies:
3883 //
John Kessenich4bf71552016-09-02 11:20:21 -06003884 // - "in" parameters not marked as "const" can be written to without modifying the calling
3885 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003886 //
3887 // - "const in" parameters can just be the r-value, as no writes need occur.
3888 //
John Kessenich4bf71552016-09-02 11:20:21 -06003889 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3890 // 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 -06003891
3892 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003893 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003894 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3895
John Kessenichfad62972017-07-18 02:35:46 -06003896 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3897 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003898
John Kessenichfad62972017-07-18 02:35:46 -06003899 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003900 for (int p = 0; p < (int)parameters.size(); ++p) {
3901 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3902 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003903 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003904 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003905 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003906 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3907 else
John Kessenich4bf71552016-09-02 11:20:21 -06003908 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003909 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003910 paramTypes.push_back(typeId);
3911 }
3912
3913 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003914 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3915 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003916 glslFunction->getName().c_str(), paramTypes,
3917 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003918 if (implicitThis)
3919 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003920
3921 // Track function to emit/call later
3922 functionMap[glslFunction->getName().c_str()] = function;
3923
3924 // Set the parameter id's
3925 for (int p = 0; p < (int)parameters.size(); ++p) {
3926 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3927 // give a name too
3928 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3929 }
3930 }
3931}
3932
3933// Process all the initializers, while skipping the functions and link objects
3934void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3935{
3936 builder.setBuildPoint(shaderEntry->getLastBlock());
3937 for (int i = 0; i < (int)initializers.size(); ++i) {
3938 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3939 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3940
3941 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003942 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003943 initializer->traverse(this);
3944 }
3945 }
3946}
3947
3948// Process all the functions, while skipping initializers.
3949void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3950{
3951 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3952 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003953 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003954 node->traverse(this);
3955 }
3956}
3957
3958void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3959{
qining25262b32016-05-06 17:25:16 -04003960 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003961 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003962 currentFunction = functionMap[node->getName().c_str()];
3963 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003964 builder.setBuildPoint(functionBlock);
3965}
3966
Rex Xu04db3f52015-09-16 11:44:02 +08003967void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003968{
Rex Xufc618912015-09-09 16:42:49 +08003969 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003970
3971 glslang::TSampler sampler = {};
3972 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003973#ifdef AMD_EXTENSIONS
3974 bool f16ShadowCompare = false;
3975#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003976 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003977 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3978 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003979#ifdef AMD_EXTENSIONS
3980 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3981#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003982 }
3983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3985 builder.clearAccessChain();
3986 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003987
3988 // Special case l-value operands
3989 bool lvalue = false;
3990 switch (node.getOp()) {
3991 case glslang::EOpImageAtomicAdd:
3992 case glslang::EOpImageAtomicMin:
3993 case glslang::EOpImageAtomicMax:
3994 case glslang::EOpImageAtomicAnd:
3995 case glslang::EOpImageAtomicOr:
3996 case glslang::EOpImageAtomicXor:
3997 case glslang::EOpImageAtomicExchange:
3998 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003999 case glslang::EOpImageAtomicLoad:
4000 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004001 if (i == 0)
4002 lvalue = true;
4003 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004004 case glslang::EOpSparseImageLoad:
4005 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4006 lvalue = true;
4007 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004008#ifdef AMD_EXTENSIONS
4009 case glslang::EOpSparseTexture:
4010 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4011 lvalue = true;
4012 break;
4013 case glslang::EOpSparseTextureClamp:
4014 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4015 lvalue = true;
4016 break;
4017 case glslang::EOpSparseTextureLod:
4018 case glslang::EOpSparseTextureOffset:
4019 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4020 lvalue = true;
4021 break;
4022#else
Rex Xu48edadf2015-12-31 16:11:41 +08004023 case glslang::EOpSparseTexture:
4024 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4025 lvalue = true;
4026 break;
4027 case glslang::EOpSparseTextureClamp:
4028 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4029 lvalue = true;
4030 break;
4031 case glslang::EOpSparseTextureLod:
4032 case glslang::EOpSparseTextureOffset:
4033 if (i == 3)
4034 lvalue = true;
4035 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004036#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004037 case glslang::EOpSparseTextureFetch:
4038 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4039 lvalue = true;
4040 break;
4041 case glslang::EOpSparseTextureFetchOffset:
4042 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4043 lvalue = true;
4044 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004045#ifdef AMD_EXTENSIONS
4046 case glslang::EOpSparseTextureLodOffset:
4047 case glslang::EOpSparseTextureGrad:
4048 case glslang::EOpSparseTextureOffsetClamp:
4049 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4050 lvalue = true;
4051 break;
4052 case glslang::EOpSparseTextureGradOffset:
4053 case glslang::EOpSparseTextureGradClamp:
4054 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4055 lvalue = true;
4056 break;
4057 case glslang::EOpSparseTextureGradOffsetClamp:
4058 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4059 lvalue = true;
4060 break;
4061#else
Rex Xu48edadf2015-12-31 16:11:41 +08004062 case glslang::EOpSparseTextureLodOffset:
4063 case glslang::EOpSparseTextureGrad:
4064 case glslang::EOpSparseTextureOffsetClamp:
4065 if (i == 4)
4066 lvalue = true;
4067 break;
4068 case glslang::EOpSparseTextureGradOffset:
4069 case glslang::EOpSparseTextureGradClamp:
4070 if (i == 5)
4071 lvalue = true;
4072 break;
4073 case glslang::EOpSparseTextureGradOffsetClamp:
4074 if (i == 6)
4075 lvalue = true;
4076 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004077#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004078 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004079 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4080 lvalue = true;
4081 break;
4082 case glslang::EOpSparseTextureGatherOffset:
4083 case glslang::EOpSparseTextureGatherOffsets:
4084 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4085 lvalue = true;
4086 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004087#ifdef AMD_EXTENSIONS
4088 case glslang::EOpSparseTextureGatherLod:
4089 if (i == 3)
4090 lvalue = true;
4091 break;
4092 case glslang::EOpSparseTextureGatherLodOffset:
4093 case glslang::EOpSparseTextureGatherLodOffsets:
4094 if (i == 4)
4095 lvalue = true;
4096 break;
Rex Xu129799a2017-07-05 17:23:28 +08004097 case glslang::EOpSparseImageLoadLod:
4098 if (i == 3)
4099 lvalue = true;
4100 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004101#endif
Chao Chen3a137962018-09-19 11:41:27 -07004102#ifdef NV_EXTENSIONS
4103 case glslang::EOpImageSampleFootprintNV:
4104 if (i == 4)
4105 lvalue = true;
4106 break;
4107 case glslang::EOpImageSampleFootprintClampNV:
4108 case glslang::EOpImageSampleFootprintLodNV:
4109 if (i == 5)
4110 lvalue = true;
4111 break;
4112 case glslang::EOpImageSampleFootprintGradNV:
4113 if (i == 6)
4114 lvalue = true;
4115 break;
4116 case glslang::EOpImageSampleFootprintGradClampNV:
4117 if (i == 7)
4118 lvalue = true;
4119 break;
4120#endif
Rex Xufc618912015-09-09 16:42:49 +08004121 default:
4122 break;
4123 }
4124
Rex Xu6b86d492015-09-16 17:48:22 +08004125 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004126 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004127 else
John Kessenich32cfd492016-02-02 12:37:46 -07004128 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004129 }
4130}
4131
John Kessenichfc51d282015-08-19 13:34:18 -06004132void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004133{
John Kessenichfc51d282015-08-19 13:34:18 -06004134 builder.clearAccessChain();
4135 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004136 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004137}
John Kessenich140f3df2015-06-26 16:58:36 -06004138
John Kessenichfc51d282015-08-19 13:34:18 -06004139spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4140{
John Kesseniche485c7a2017-05-31 18:50:53 -06004141 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004142 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004143
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004145
John Kessenichfc51d282015-08-19 13:34:18 -06004146 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004147
4148 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4149 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4150 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004151#ifdef AMD_EXTENSIONS
4152 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4153 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4154 : false;
4155#endif
4156
John Kessenichfc51d282015-08-19 13:34:18 -06004157 std::vector<spv::Id> arguments;
4158 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004159 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004160 else
4161 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004162 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004163
4164 spv::Builder::TextureParameters params = { };
4165 params.sampler = arguments[0];
4166
Rex Xu04db3f52015-09-16 11:44:02 +08004167 glslang::TCrackedTextureOp cracked;
4168 node->crackTexture(sampler, cracked);
4169
amhagan05506bb2017-06-13 16:53:02 -04004170 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004171
John Kessenichfc51d282015-08-19 13:34:18 -06004172 // Check for queries
4173 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004174 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4175 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004176 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004177
John Kessenichfc51d282015-08-19 13:34:18 -06004178 switch (node->getOp()) {
4179 case glslang::EOpImageQuerySize:
4180 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004181 if (arguments.size() > 1) {
4182 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004183 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004184 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004185 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004186 case glslang::EOpImageQuerySamples:
4187 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004188 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004189 case glslang::EOpTextureQueryLod:
4190 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004191 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004192 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004193 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004194 case glslang::EOpSparseTexelsResident:
4195 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004196 default:
4197 assert(0);
4198 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004199 }
John Kessenich140f3df2015-06-26 16:58:36 -06004200 }
4201
LoopDawg4425f242018-02-18 11:40:01 -07004202 int components = node->getType().getVectorSize();
4203
4204 if (node->getOp() == glslang::EOpTextureFetch) {
4205 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4206 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4207 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4208 // here around e.g. which ones return scalars or other types.
4209 components = 4;
4210 }
4211
4212 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4213
4214 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4215
Rex Xufc618912015-09-09 16:42:49 +08004216 // Check for image functions other than queries
4217 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004218 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004219 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004220 spv::IdImmediate image = { true, *(opIt++) };
4221 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004222
4223 // Handle subpass operations
4224 // TODO: GLSL should change to have the "MS" only on the type rather than the
4225 // built-in function.
4226 if (cracked.subpass) {
4227 // add on the (0,0) coordinate
4228 spv::Id zero = builder.makeIntConstant(0);
4229 std::vector<spv::Id> comps;
4230 comps.push_back(zero);
4231 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004232 spv::IdImmediate coord = { true,
4233 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4234 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004235 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004236 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4237 operands.push_back(imageOperands);
4238 spv::IdImmediate imageOperand = { true, *(opIt++) };
4239 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004240 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004241 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4242 builder.setPrecision(result, precision);
4243 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004244 }
4245
John Kessenich149afc32018-08-14 13:31:43 -06004246 spv::IdImmediate coord = { true, *(opIt++) };
4247 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004248#ifdef AMD_EXTENSIONS
4249 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4250#else
John Kessenich56bab042015-09-16 10:54:31 -06004251 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004252#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004253 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004254 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004255 mask = mask | spv::ImageOperandsSampleMask;
4256 }
Rex Xu129799a2017-07-05 17:23:28 +08004257#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004258 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004259 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4260 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004261 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004262 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004263#endif
4264 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4265 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4266 if (mask) {
4267 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4268 operands.push_back(imageOperands);
4269 }
4270 if (mask & spv::ImageOperandsSampleMask) {
4271 spv::IdImmediate imageOperand = { true, *opIt++ };
4272 operands.push_back(imageOperand);
4273 }
4274#ifdef AMD_EXTENSIONS
4275 if (mask & spv::ImageOperandsLodMask) {
4276 spv::IdImmediate imageOperand = { true, *opIt++ };
4277 operands.push_back(imageOperand);
4278 }
4279#endif
4280 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4281 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4282 operands.push_back(imageOperand);
4283 }
4284
John Kessenich149afc32018-08-14 13:31:43 -06004285 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004286 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004287
John Kessenich149afc32018-08-14 13:31:43 -06004288 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004289 builder.setPrecision(result[0], precision);
4290
4291 // If needed, add a conversion constructor to the proper size.
4292 if (components != node->getType().getVectorSize())
4293 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4294
4295 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004296#ifdef AMD_EXTENSIONS
4297 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4298#else
John Kessenich56bab042015-09-16 10:54:31 -06004299 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004300#endif
Rex Xu129799a2017-07-05 17:23:28 +08004301
Jeff Bolz36831c92018-09-05 10:11:41 -05004302 // Push the texel value before the operands
4303#ifdef AMD_EXTENSIONS
4304 if (sampler.ms || cracked.lod) {
4305#else
4306 if (sampler.ms) {
4307#endif
John Kessenich149afc32018-08-14 13:31:43 -06004308 spv::IdImmediate texel = { true, *(opIt + 1) };
4309 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004310 } else {
4311 spv::IdImmediate texel = { true, *opIt };
4312 operands.push_back(texel);
4313 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004314
4315 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4316 if (sampler.ms) {
4317 mask = mask | spv::ImageOperandsSampleMask;
4318 }
4319#ifdef AMD_EXTENSIONS
4320 if (cracked.lod) {
4321 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4322 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4323 mask = mask | spv::ImageOperandsLodMask;
4324 }
4325#endif
4326 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4327 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4328 if (mask) {
4329 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4330 operands.push_back(imageOperands);
4331 }
4332 if (mask & spv::ImageOperandsSampleMask) {
4333 spv::IdImmediate imageOperand = { true, *opIt++ };
4334 operands.push_back(imageOperand);
4335 }
4336#ifdef AMD_EXTENSIONS
4337 if (mask & spv::ImageOperandsLodMask) {
4338 spv::IdImmediate imageOperand = { true, *opIt++ };
4339 operands.push_back(imageOperand);
4340 }
4341#endif
4342 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4343 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4344 operands.push_back(imageOperand);
4345 }
4346
John Kessenich56bab042015-09-16 10:54:31 -06004347 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004348 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004349 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004350 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004351#ifdef AMD_EXTENSIONS
4352 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4353#else
Rex Xu5eafa472016-02-19 22:24:03 +08004354 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004355#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004356 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004357 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004358 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4359
Jeff Bolz36831c92018-09-05 10:11:41 -05004360 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004361 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004362 mask = mask | spv::ImageOperandsSampleMask;
4363 }
Rex Xu129799a2017-07-05 17:23:28 +08004364#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004365 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004366 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4367 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4368
Jeff Bolz36831c92018-09-05 10:11:41 -05004369 mask = mask | spv::ImageOperandsLodMask;
4370 }
4371#endif
4372 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4373 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4374 if (mask) {
4375 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004376 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004377 }
4378 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004379 spv::IdImmediate imageOperand = { true, *opIt++ };
4380 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004381 }
4382#ifdef AMD_EXTENSIONS
4383 if (mask & spv::ImageOperandsLodMask) {
4384 spv::IdImmediate imageOperand = { true, *opIt++ };
4385 operands.push_back(imageOperand);
4386 }
Rex Xu129799a2017-07-05 17:23:28 +08004387#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004388 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4389 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4390 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004391 }
4392
4393 // Create the return type that was a special structure
4394 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004395 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004396 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4397 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4398
4399 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4400
4401 // Decode the return type
4402 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4403 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004404 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004405 // Process image atomic operations
4406
4407 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4408 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004409 // For non-MS, the sample value should be 0
4410 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4411 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004412
Jeff Bolz36831c92018-09-05 10:11:41 -05004413 spv::Id resultTypeId;
4414 // imageAtomicStore has a void return type so base the pointer type on
4415 // the type of the value operand.
4416 if (node->getOp() == glslang::EOpImageAtomicStore) {
4417 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4418 } else {
4419 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4420 }
John Kessenich56bab042015-09-16 10:54:31 -06004421 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004422
4423 std::vector<spv::Id> operands;
4424 operands.push_back(pointer);
4425 for (; opIt != arguments.end(); ++opIt)
4426 operands.push_back(*opIt);
4427
John Kessenich8c8505c2016-07-26 12:50:38 -06004428 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004429 }
4430 }
4431
amhagan05506bb2017-06-13 16:53:02 -04004432#ifdef AMD_EXTENSIONS
4433 // Check for fragment mask functions other than queries
4434 if (cracked.fragMask) {
4435 assert(sampler.ms);
4436
4437 auto opIt = arguments.begin();
4438 std::vector<spv::Id> operands;
4439
4440 // Extract the image if necessary
4441 if (builder.isSampledImage(params.sampler))
4442 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4443
4444 operands.push_back(params.sampler);
4445 ++opIt;
4446
4447 if (sampler.isSubpass()) {
4448 // add on the (0,0) coordinate
4449 spv::Id zero = builder.makeIntConstant(0);
4450 std::vector<spv::Id> comps;
4451 comps.push_back(zero);
4452 comps.push_back(zero);
4453 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4454 }
4455
4456 for (; opIt != arguments.end(); ++opIt)
4457 operands.push_back(*opIt);
4458
4459 spv::Op fragMaskOp = spv::OpNop;
4460 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4461 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4462 else if (node->getOp() == glslang::EOpFragmentFetch)
4463 fragMaskOp = spv::OpFragmentFetchAMD;
4464
4465 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4466 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4467 return builder.createOp(fragMaskOp, resultType(), operands);
4468 }
4469#endif
4470
Rex Xufc618912015-09-09 16:42:49 +08004471 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004472 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004473#ifdef NV_EXTENSIONS
4474 bool imageFootprint = node->isImageFootprint();
4475#endif
4476
Rex Xu71519fe2015-11-11 15:35:47 +08004477 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4478
John Kessenichfc51d282015-08-19 13:34:18 -06004479 // check for bias argument
4480 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004481#ifdef AMD_EXTENSIONS
4482 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4483#else
Rex Xu71519fe2015-11-11 15:35:47 +08004484 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004485#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004486 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004487#ifdef AMD_EXTENSIONS
4488 if (cracked.gather)
4489 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004490
4491 if (f16ShadowCompare)
4492 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004493#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004494 if (cracked.offset)
4495 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004496#ifdef AMD_EXTENSIONS
4497 else if (cracked.offsets)
4498 ++nonBiasArgCount;
4499#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004500 if (cracked.grad)
4501 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004502 if (cracked.lodClamp)
4503 ++nonBiasArgCount;
4504 if (sparse)
4505 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004506#ifdef NV_EXTENSIONS
4507 if (imageFootprint)
4508 //Following three extra arguments
4509 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4510 nonBiasArgCount += 3;
4511#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004512 if ((int)arguments.size() > nonBiasArgCount)
4513 bias = true;
4514 }
4515
John Kessenicha5c33d62016-06-02 23:45:21 -06004516 // See if the sampler param should really be just the SPV image part
4517 if (cracked.fetch) {
4518 // a fetch needs to have the image extracted first
4519 if (builder.isSampledImage(params.sampler))
4520 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4521 }
4522
Rex Xu225e0fc2016-11-17 17:47:59 +08004523#ifdef AMD_EXTENSIONS
4524 if (cracked.gather) {
4525 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4526 if (bias || cracked.lod ||
4527 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4528 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004529 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004530 }
4531 }
4532#endif
4533
John Kessenichfc51d282015-08-19 13:34:18 -06004534 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004535
John Kessenichfc51d282015-08-19 13:34:18 -06004536 params.coords = arguments[1];
4537 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004538 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004539
4540 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004541#ifdef AMD_EXTENSIONS
4542 if (cubeCompare || f16ShadowCompare) {
4543#else
Rex Xu48edadf2015-12-31 16:11:41 +08004544 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004545#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004546 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004547 ++extraArgs;
4548 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004549 params.Dref = arguments[2];
4550 ++extraArgs;
4551 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004552 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004553 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004554 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004555 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004556 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004557 dRefComp = builder.getNumComponents(params.coords) - 1;
4558 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004559 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4560 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004561
4562 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004563 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004564 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004565 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004566 } else if (glslangIntermediate->getStage() != EShLangFragment
4567#ifdef NV_EXTENSIONS
4568 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4569 && !(glslangIntermediate->getStage() == EShLangCompute &&
4570 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4571#endif
4572 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004573 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4574 noImplicitLod = true;
4575 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004576
4577 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004578 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004579 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004580 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004581 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004582
4583 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004584 if (cracked.grad) {
4585 params.gradX = arguments[2 + extraArgs];
4586 params.gradY = arguments[3 + extraArgs];
4587 extraArgs += 2;
4588 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004589
4590 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004591 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004592 params.offset = arguments[2 + extraArgs];
4593 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004594 } else if (cracked.offsets) {
4595 params.offsets = arguments[2 + extraArgs];
4596 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004597 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004598
4599 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004600 if (cracked.lodClamp) {
4601 params.lodClamp = arguments[2 + extraArgs];
4602 ++extraArgs;
4603 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004604 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004605 if (sparse) {
4606 params.texelOut = arguments[2 + extraArgs];
4607 ++extraArgs;
4608 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004609
John Kessenich76d4dfc2016-06-16 12:43:23 -06004610 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004611 if (cracked.gather && ! sampler.shadow) {
4612 // default component is 0, if missing, otherwise an argument
4613 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004614 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004615 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004616 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004617 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004618 }
Chao Chen3a137962018-09-19 11:41:27 -07004619#ifdef NV_EXTENSIONS
4620 spv::Id resultStruct = spv::NoResult;
4621 if (imageFootprint) {
4622 //Following three extra arguments
4623 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4624 params.granularity = arguments[2 + extraArgs];
4625 params.coarse = arguments[3 + extraArgs];
4626 resultStruct = arguments[4 + extraArgs];
4627 extraArgs += 3;
4628 }
4629#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004630 // bias
4631 if (bias) {
4632 params.bias = arguments[2 + extraArgs];
4633 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004634 }
John Kessenichfc51d282015-08-19 13:34:18 -06004635
Chao Chen3a137962018-09-19 11:41:27 -07004636#ifdef NV_EXTENSIONS
4637 if (imageFootprint) {
4638 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4639 builder.addCapability(spv::CapabilityImageFootprintNV);
4640
4641
4642 //resultStructType(OpenGL type) contains 5 elements:
4643 //struct gl_TextureFootprint2DNV {
4644 // uvec2 anchor;
4645 // uvec2 offset;
4646 // uvec2 mask;
4647 // uint lod;
4648 // uint granularity;
4649 //};
4650 //or
4651 //struct gl_TextureFootprint3DNV {
4652 // uvec3 anchor;
4653 // uvec3 offset;
4654 // uvec2 mask;
4655 // uint lod;
4656 // uint granularity;
4657 //};
4658 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4659 assert(builder.isStructType(resultStructType));
4660
4661 //resType (SPIR-V type) contains 6 elements:
4662 //Member 0 must be a Boolean type scalar(LOD),
4663 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4664 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4665 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4666 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4667 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4668 std::vector<spv::Id> members;
4669 members.push_back(resultType());
4670 for (int i = 0; i < 5; i++) {
4671 members.push_back(builder.getContainedTypeId(resultStructType, i));
4672 }
4673 spv::Id resType = builder.makeStructType(members, "ResType");
4674
4675 //call ImageFootprintNV
4676 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4677
4678 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4679 for (int i = 0; i < 5; i++) {
4680 builder.clearAccessChain();
4681 builder.setAccessChainLValue(resultStruct);
4682
4683 //Accessing to a struct we created, no coherent flag is set
4684 spv::Builder::AccessChain::CoherentFlags flags;
4685 flags.clear();
4686
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004687 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004688 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4689 }
4690 return builder.createCompositeExtract(res, resultType(), 0);
4691 }
4692#endif
4693
John Kessenich65336482016-06-16 14:06:26 -06004694 // projective component (might not to move)
4695 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4696 // are divided by the last component of P."
4697 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4698 // unused components will appear after all used components."
4699 if (cracked.proj) {
4700 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4701 int projTargetComp;
4702 switch (sampler.dim) {
4703 case glslang::Esd1D: projTargetComp = 1; break;
4704 case glslang::Esd2D: projTargetComp = 2; break;
4705 case glslang::EsdRect: projTargetComp = 2; break;
4706 default: projTargetComp = projSourceComp; break;
4707 }
4708 // copy the projective coordinate if we have to
4709 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004710 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004711 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4712 projSourceComp);
4713 params.coords = builder.createCompositeInsert(projComp, params.coords,
4714 builder.getTypeId(params.coords), projTargetComp);
4715 }
4716 }
4717
Jeff Bolz36831c92018-09-05 10:11:41 -05004718 // nonprivate
4719 if (imageType.getQualifier().nonprivate) {
4720 params.nonprivate = true;
4721 }
4722
4723 // volatile
4724 if (imageType.getQualifier().volatil) {
4725 params.volatil = true;
4726 }
4727
St0fFa1184dd2018-04-09 21:08:14 +02004728 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004729 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004730 );
LoopDawg4425f242018-02-18 11:40:01 -07004731
4732 if (components != node->getType().getVectorSize())
4733 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4734
4735 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004736}
4737
4738spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4739{
4740 // Grab the function's pointer from the previously created function
4741 spv::Function* function = functionMap[node->getName().c_str()];
4742 if (! function)
4743 return 0;
4744
4745 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4746 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4747
4748 // See comments in makeFunctions() for details about the semantics for parameter passing.
4749 //
4750 // These imply we need a four step process:
4751 // 1. Evaluate the arguments
4752 // 2. Allocate and make copies of in, out, and inout arguments
4753 // 3. Make the call
4754 // 4. Copy back the results
4755
John Kessenichd3ed90b2018-05-04 11:43:03 -06004756 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004757 std::vector<spv::Builder::AccessChain> lValues;
4758 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004759 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004760 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004761 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004762 // build l-value
4763 builder.clearAccessChain();
4764 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004765 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004766 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004767 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004768 // save l-value
4769 lValues.push_back(builder.getAccessChain());
4770 } else {
4771 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004772 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004773 }
4774 }
4775
4776 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4777 // copy the original into that space.
4778 //
4779 // Also, build up the list of actual arguments to pass in for the call
4780 int lValueCount = 0;
4781 int rValueCount = 0;
4782 std::vector<spv::Id> spvArgs;
4783 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4784 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004785 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004786 builder.setAccessChain(lValues[lValueCount]);
4787 arg = builder.accessChainGetLValue();
4788 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004789 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004790 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004791 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004792 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4793 // need to copy the input into output space
4794 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004795 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004796 builder.clearAccessChain();
4797 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004798 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004799 }
4800 ++lValueCount;
4801 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004802 // process r-value, which involves a copy for a type mismatch
4803 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4804 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4805 builder.clearAccessChain();
4806 builder.setAccessChainLValue(argCopy);
4807 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4808 arg = builder.createLoad(argCopy);
4809 } else
4810 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004811 ++rValueCount;
4812 }
4813 spvArgs.push_back(arg);
4814 }
4815
4816 // 3. Make the call.
4817 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004818 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004819
4820 // 4. Copy back out an "out" arguments.
4821 lValueCount = 0;
4822 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004823 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004824 ++lValueCount;
4825 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004826 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4827 spv::Id copy = builder.createLoad(spvArgs[a]);
4828 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004829 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004830 }
4831 ++lValueCount;
4832 }
4833 }
4834
4835 return result;
4836}
4837
4838// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004839spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004840 spv::Id typeId, spv::Id left, spv::Id right,
4841 glslang::TBasicType typeProxy, bool reduceComparison)
4842{
John Kessenich66011cb2018-03-06 16:12:04 -07004843 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4844 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004845 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004846
4847 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004848 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004849 bool comparison = false;
4850
4851 switch (op) {
4852 case glslang::EOpAdd:
4853 case glslang::EOpAddAssign:
4854 if (isFloat)
4855 binOp = spv::OpFAdd;
4856 else
4857 binOp = spv::OpIAdd;
4858 break;
4859 case glslang::EOpSub:
4860 case glslang::EOpSubAssign:
4861 if (isFloat)
4862 binOp = spv::OpFSub;
4863 else
4864 binOp = spv::OpISub;
4865 break;
4866 case glslang::EOpMul:
4867 case glslang::EOpMulAssign:
4868 if (isFloat)
4869 binOp = spv::OpFMul;
4870 else
4871 binOp = spv::OpIMul;
4872 break;
4873 case glslang::EOpVectorTimesScalar:
4874 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004875 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004876 if (builder.isVector(right))
4877 std::swap(left, right);
4878 assert(builder.isScalar(right));
4879 needMatchingVectors = false;
4880 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004881 } else if (isFloat)
4882 binOp = spv::OpFMul;
4883 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004884 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004885 break;
4886 case glslang::EOpVectorTimesMatrix:
4887 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004888 binOp = spv::OpVectorTimesMatrix;
4889 break;
4890 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004891 binOp = spv::OpMatrixTimesVector;
4892 break;
4893 case glslang::EOpMatrixTimesScalar:
4894 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004895 binOp = spv::OpMatrixTimesScalar;
4896 break;
4897 case glslang::EOpMatrixTimesMatrix:
4898 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004899 binOp = spv::OpMatrixTimesMatrix;
4900 break;
4901 case glslang::EOpOuterProduct:
4902 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004903 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004904 break;
4905
4906 case glslang::EOpDiv:
4907 case glslang::EOpDivAssign:
4908 if (isFloat)
4909 binOp = spv::OpFDiv;
4910 else if (isUnsigned)
4911 binOp = spv::OpUDiv;
4912 else
4913 binOp = spv::OpSDiv;
4914 break;
4915 case glslang::EOpMod:
4916 case glslang::EOpModAssign:
4917 if (isFloat)
4918 binOp = spv::OpFMod;
4919 else if (isUnsigned)
4920 binOp = spv::OpUMod;
4921 else
4922 binOp = spv::OpSMod;
4923 break;
4924 case glslang::EOpRightShift:
4925 case glslang::EOpRightShiftAssign:
4926 if (isUnsigned)
4927 binOp = spv::OpShiftRightLogical;
4928 else
4929 binOp = spv::OpShiftRightArithmetic;
4930 break;
4931 case glslang::EOpLeftShift:
4932 case glslang::EOpLeftShiftAssign:
4933 binOp = spv::OpShiftLeftLogical;
4934 break;
4935 case glslang::EOpAnd:
4936 case glslang::EOpAndAssign:
4937 binOp = spv::OpBitwiseAnd;
4938 break;
4939 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004940 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004941 binOp = spv::OpLogicalAnd;
4942 break;
4943 case glslang::EOpInclusiveOr:
4944 case glslang::EOpInclusiveOrAssign:
4945 binOp = spv::OpBitwiseOr;
4946 break;
4947 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004948 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 binOp = spv::OpLogicalOr;
4950 break;
4951 case glslang::EOpExclusiveOr:
4952 case glslang::EOpExclusiveOrAssign:
4953 binOp = spv::OpBitwiseXor;
4954 break;
4955 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004956 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004957 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004958 break;
4959
4960 case glslang::EOpLessThan:
4961 case glslang::EOpGreaterThan:
4962 case glslang::EOpLessThanEqual:
4963 case glslang::EOpGreaterThanEqual:
4964 case glslang::EOpEqual:
4965 case glslang::EOpNotEqual:
4966 case glslang::EOpVectorEqual:
4967 case glslang::EOpVectorNotEqual:
4968 comparison = true;
4969 break;
4970 default:
4971 break;
4972 }
4973
John Kessenich7c1aa102015-10-15 13:29:11 -06004974 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004975 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004976 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004977 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4978 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004979 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004980
4981 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004982 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004983 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004984
qining25262b32016-05-06 17:25:16 -04004985 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004986 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004987 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004988 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004989 }
4990
4991 if (! comparison)
4992 return 0;
4993
John Kessenich7c1aa102015-10-15 13:29:11 -06004994 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004995
John Kessenich4583b612016-08-07 19:14:22 -06004996 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004997 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4998 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004999 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005000 return result;
5001 }
John Kessenich140f3df2015-06-26 16:58:36 -06005002
5003 switch (op) {
5004 case glslang::EOpLessThan:
5005 if (isFloat)
5006 binOp = spv::OpFOrdLessThan;
5007 else if (isUnsigned)
5008 binOp = spv::OpULessThan;
5009 else
5010 binOp = spv::OpSLessThan;
5011 break;
5012 case glslang::EOpGreaterThan:
5013 if (isFloat)
5014 binOp = spv::OpFOrdGreaterThan;
5015 else if (isUnsigned)
5016 binOp = spv::OpUGreaterThan;
5017 else
5018 binOp = spv::OpSGreaterThan;
5019 break;
5020 case glslang::EOpLessThanEqual:
5021 if (isFloat)
5022 binOp = spv::OpFOrdLessThanEqual;
5023 else if (isUnsigned)
5024 binOp = spv::OpULessThanEqual;
5025 else
5026 binOp = spv::OpSLessThanEqual;
5027 break;
5028 case glslang::EOpGreaterThanEqual:
5029 if (isFloat)
5030 binOp = spv::OpFOrdGreaterThanEqual;
5031 else if (isUnsigned)
5032 binOp = spv::OpUGreaterThanEqual;
5033 else
5034 binOp = spv::OpSGreaterThanEqual;
5035 break;
5036 case glslang::EOpEqual:
5037 case glslang::EOpVectorEqual:
5038 if (isFloat)
5039 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005040 else if (isBool)
5041 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 else
5043 binOp = spv::OpIEqual;
5044 break;
5045 case glslang::EOpNotEqual:
5046 case glslang::EOpVectorNotEqual:
5047 if (isFloat)
5048 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005049 else if (isBool)
5050 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005051 else
5052 binOp = spv::OpINotEqual;
5053 break;
5054 default:
5055 break;
5056 }
5057
qining25262b32016-05-06 17:25:16 -04005058 if (binOp != spv::OpNop) {
5059 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005060 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005061 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005062 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005063 }
John Kessenich140f3df2015-06-26 16:58:36 -06005064
5065 return 0;
5066}
5067
John Kessenich04bb8a02015-12-12 12:28:14 -07005068//
5069// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5070// These can be any of:
5071//
5072// matrix * scalar
5073// scalar * matrix
5074// matrix * matrix linear algebraic
5075// matrix * vector
5076// vector * matrix
5077// matrix * matrix componentwise
5078// matrix op matrix op in {+, -, /}
5079// matrix op scalar op in {+, -, /}
5080// scalar op matrix op in {+, -, /}
5081//
John Kessenichead86222018-03-28 18:01:20 -06005082spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5083 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005084{
5085 bool firstClass = true;
5086
5087 // First, handle first-class matrix operations (* and matrix/scalar)
5088 switch (op) {
5089 case spv::OpFDiv:
5090 if (builder.isMatrix(left) && builder.isScalar(right)) {
5091 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005092 spv::Id resultType = builder.getTypeId(right);
5093 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005094 op = spv::OpMatrixTimesScalar;
5095 } else
5096 firstClass = false;
5097 break;
5098 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005099 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005100 std::swap(left, right);
5101 assert(builder.isScalar(right));
5102 break;
5103 case spv::OpVectorTimesMatrix:
5104 assert(builder.isVector(left));
5105 assert(builder.isMatrix(right));
5106 break;
5107 case spv::OpMatrixTimesVector:
5108 assert(builder.isMatrix(left));
5109 assert(builder.isVector(right));
5110 break;
5111 case spv::OpMatrixTimesMatrix:
5112 assert(builder.isMatrix(left));
5113 assert(builder.isMatrix(right));
5114 break;
5115 default:
5116 firstClass = false;
5117 break;
5118 }
5119
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005120 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5121 firstClass = true;
5122
qining25262b32016-05-06 17:25:16 -04005123 if (firstClass) {
5124 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005125 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005126 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005127 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005128 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005129
LoopDawg592860c2016-06-09 08:57:35 -06005130 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005131 // The result type of all of them is the same type as the (a) matrix operand.
5132 // The algorithm is to:
5133 // - break the matrix(es) into vectors
5134 // - smear any scalar to a vector
5135 // - do vector operations
5136 // - make a matrix out the vector results
5137 switch (op) {
5138 case spv::OpFAdd:
5139 case spv::OpFSub:
5140 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005141 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005142 case spv::OpFMul:
5143 {
5144 // one time set up...
5145 bool leftMat = builder.isMatrix(left);
5146 bool rightMat = builder.isMatrix(right);
5147 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5148 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5149 spv::Id scalarType = builder.getScalarTypeId(typeId);
5150 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5151 std::vector<spv::Id> results;
5152 spv::Id smearVec = spv::NoResult;
5153 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005154 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005155 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005156 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005157
5158 // do each vector op
5159 for (unsigned int c = 0; c < numCols; ++c) {
5160 std::vector<unsigned int> indexes;
5161 indexes.push_back(c);
5162 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5163 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005164 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005165 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005166 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005167 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005168 }
5169
5170 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005171 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005172 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005173 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005174 }
5175 default:
5176 assert(0);
5177 return spv::NoResult;
5178 }
5179}
5180
John Kessenichead86222018-03-28 18:01:20 -06005181spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5182 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005183{
5184 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005185 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005186 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005187 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5188 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005189
5190 switch (op) {
5191 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005192 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005193 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005194 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005195 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005196 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005197 unaryOp = spv::OpSNegate;
5198 break;
5199
5200 case glslang::EOpLogicalNot:
5201 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005202 unaryOp = spv::OpLogicalNot;
5203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005204 case glslang::EOpBitwiseNot:
5205 unaryOp = spv::OpNot;
5206 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005207
John Kessenich140f3df2015-06-26 16:58:36 -06005208 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpTranspose:
5215 unaryOp = spv::OpTranspose;
5216 break;
5217
5218 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005219 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005220 break;
5221 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005222 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 break;
5224 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005225 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 break;
5227 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005229 break;
5230 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
5236 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005237 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005238 break;
5239 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 break;
5242
5243 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005244 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
5246 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005247 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 break;
5249 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005250 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
5252 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
5255 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005257 break;
5258 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005259 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005260 break;
5261
5262 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005263 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005264 break;
5265 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268
5269 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005270 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005273 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005279 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005280 break;
5281 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005282 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287
5288 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005289 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005292 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005295 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005296 break;
5297 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005298 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005299 break;
5300 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005301 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005302 break;
5303 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005304 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005305 break;
5306
5307 case glslang::EOpIsNan:
5308 unaryOp = spv::OpIsNan;
5309 break;
5310 case glslang::EOpIsInf:
5311 unaryOp = spv::OpIsInf;
5312 break;
LoopDawg592860c2016-06-09 08:57:35 -06005313 case glslang::EOpIsFinite:
5314 unaryOp = spv::OpIsFinite;
5315 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005316
Rex Xucbc426e2015-12-15 16:03:10 +08005317 case glslang::EOpFloatBitsToInt:
5318 case glslang::EOpFloatBitsToUint:
5319 case glslang::EOpIntBitsToFloat:
5320 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005321 case glslang::EOpDoubleBitsToInt64:
5322 case glslang::EOpDoubleBitsToUint64:
5323 case glslang::EOpInt64BitsToDouble:
5324 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005325 case glslang::EOpFloat16BitsToInt16:
5326 case glslang::EOpFloat16BitsToUint16:
5327 case glslang::EOpInt16BitsToFloat16:
5328 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005329 unaryOp = spv::OpBitcast;
5330 break;
5331
John Kessenich140f3df2015-06-26 16:58:36 -06005332 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005333 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005334 break;
5335 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005336 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005337 break;
5338 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005339 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 break;
5341 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005342 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 break;
5344 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005345 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005346 break;
5347 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005348 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005349 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005350 case glslang::EOpPackSnorm4x8:
5351 libCall = spv::GLSLstd450PackSnorm4x8;
5352 break;
5353 case glslang::EOpUnpackSnorm4x8:
5354 libCall = spv::GLSLstd450UnpackSnorm4x8;
5355 break;
5356 case glslang::EOpPackUnorm4x8:
5357 libCall = spv::GLSLstd450PackUnorm4x8;
5358 break;
5359 case glslang::EOpUnpackUnorm4x8:
5360 libCall = spv::GLSLstd450UnpackUnorm4x8;
5361 break;
5362 case glslang::EOpPackDouble2x32:
5363 libCall = spv::GLSLstd450PackDouble2x32;
5364 break;
5365 case glslang::EOpUnpackDouble2x32:
5366 libCall = spv::GLSLstd450UnpackDouble2x32;
5367 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005368
Rex Xu8ff43de2016-04-22 16:51:45 +08005369 case glslang::EOpPackInt2x32:
5370 case glslang::EOpUnpackInt2x32:
5371 case glslang::EOpPackUint2x32:
5372 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005373 case glslang::EOpPack16:
5374 case glslang::EOpPack32:
5375 case glslang::EOpPack64:
5376 case glslang::EOpUnpack32:
5377 case glslang::EOpUnpack16:
5378 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005379 case glslang::EOpPackInt2x16:
5380 case glslang::EOpUnpackInt2x16:
5381 case glslang::EOpPackUint2x16:
5382 case glslang::EOpUnpackUint2x16:
5383 case glslang::EOpPackInt4x16:
5384 case glslang::EOpUnpackInt4x16:
5385 case glslang::EOpPackUint4x16:
5386 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005387 case glslang::EOpPackFloat2x16:
5388 case glslang::EOpUnpackFloat2x16:
5389 unaryOp = spv::OpBitcast;
5390 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005391
John Kessenich140f3df2015-06-26 16:58:36 -06005392 case glslang::EOpDPdx:
5393 unaryOp = spv::OpDPdx;
5394 break;
5395 case glslang::EOpDPdy:
5396 unaryOp = spv::OpDPdy;
5397 break;
5398 case glslang::EOpFwidth:
5399 unaryOp = spv::OpFwidth;
5400 break;
5401 case glslang::EOpDPdxFine:
5402 unaryOp = spv::OpDPdxFine;
5403 break;
5404 case glslang::EOpDPdyFine:
5405 unaryOp = spv::OpDPdyFine;
5406 break;
5407 case glslang::EOpFwidthFine:
5408 unaryOp = spv::OpFwidthFine;
5409 break;
5410 case glslang::EOpDPdxCoarse:
5411 unaryOp = spv::OpDPdxCoarse;
5412 break;
5413 case glslang::EOpDPdyCoarse:
5414 unaryOp = spv::OpDPdyCoarse;
5415 break;
5416 case glslang::EOpFwidthCoarse:
5417 unaryOp = spv::OpFwidthCoarse;
5418 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005419 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005420#ifdef AMD_EXTENSIONS
5421 if (typeProxy == glslang::EbtFloat16)
5422 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5423#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005424 libCall = spv::GLSLstd450InterpolateAtCentroid;
5425 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005426 case glslang::EOpAny:
5427 unaryOp = spv::OpAny;
5428 break;
5429 case glslang::EOpAll:
5430 unaryOp = spv::OpAll;
5431 break;
5432
5433 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005434 if (isFloat)
5435 libCall = spv::GLSLstd450FAbs;
5436 else
5437 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005438 break;
5439 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 if (isFloat)
5441 libCall = spv::GLSLstd450FSign;
5442 else
5443 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005444 break;
5445
John Kessenichfc51d282015-08-19 13:34:18 -06005446 case glslang::EOpAtomicCounterIncrement:
5447 case glslang::EOpAtomicCounterDecrement:
5448 case glslang::EOpAtomicCounter:
5449 {
5450 // Handle all of the atomics in one place, in createAtomicOperation()
5451 std::vector<spv::Id> operands;
5452 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005453 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005454 }
5455
John Kessenichfc51d282015-08-19 13:34:18 -06005456 case glslang::EOpBitFieldReverse:
5457 unaryOp = spv::OpBitReverse;
5458 break;
5459 case glslang::EOpBitCount:
5460 unaryOp = spv::OpBitCount;
5461 break;
5462 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005463 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005464 break;
5465 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005466 if (isUnsigned)
5467 libCall = spv::GLSLstd450FindUMsb;
5468 else
5469 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005470 break;
5471
Rex Xu574ab042016-04-14 16:53:07 +08005472 case glslang::EOpBallot:
5473 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005474 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005475 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005476 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005477#ifdef AMD_EXTENSIONS
5478 case glslang::EOpMinInvocations:
5479 case glslang::EOpMaxInvocations:
5480 case glslang::EOpAddInvocations:
5481 case glslang::EOpMinInvocationsNonUniform:
5482 case glslang::EOpMaxInvocationsNonUniform:
5483 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005484 case glslang::EOpMinInvocationsInclusiveScan:
5485 case glslang::EOpMaxInvocationsInclusiveScan:
5486 case glslang::EOpAddInvocationsInclusiveScan:
5487 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5488 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5489 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5490 case glslang::EOpMinInvocationsExclusiveScan:
5491 case glslang::EOpMaxInvocationsExclusiveScan:
5492 case glslang::EOpAddInvocationsExclusiveScan:
5493 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5494 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5495 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005496#endif
Rex Xu51596642016-09-21 18:56:12 +08005497 {
5498 std::vector<spv::Id> operands;
5499 operands.push_back(operand);
5500 return createInvocationsOperation(op, typeId, operands, typeProxy);
5501 }
John Kessenich66011cb2018-03-06 16:12:04 -07005502 case glslang::EOpSubgroupAll:
5503 case glslang::EOpSubgroupAny:
5504 case glslang::EOpSubgroupAllEqual:
5505 case glslang::EOpSubgroupBroadcastFirst:
5506 case glslang::EOpSubgroupBallot:
5507 case glslang::EOpSubgroupInverseBallot:
5508 case glslang::EOpSubgroupBallotBitCount:
5509 case glslang::EOpSubgroupBallotInclusiveBitCount:
5510 case glslang::EOpSubgroupBallotExclusiveBitCount:
5511 case glslang::EOpSubgroupBallotFindLSB:
5512 case glslang::EOpSubgroupBallotFindMSB:
5513 case glslang::EOpSubgroupAdd:
5514 case glslang::EOpSubgroupMul:
5515 case glslang::EOpSubgroupMin:
5516 case glslang::EOpSubgroupMax:
5517 case glslang::EOpSubgroupAnd:
5518 case glslang::EOpSubgroupOr:
5519 case glslang::EOpSubgroupXor:
5520 case glslang::EOpSubgroupInclusiveAdd:
5521 case glslang::EOpSubgroupInclusiveMul:
5522 case glslang::EOpSubgroupInclusiveMin:
5523 case glslang::EOpSubgroupInclusiveMax:
5524 case glslang::EOpSubgroupInclusiveAnd:
5525 case glslang::EOpSubgroupInclusiveOr:
5526 case glslang::EOpSubgroupInclusiveXor:
5527 case glslang::EOpSubgroupExclusiveAdd:
5528 case glslang::EOpSubgroupExclusiveMul:
5529 case glslang::EOpSubgroupExclusiveMin:
5530 case glslang::EOpSubgroupExclusiveMax:
5531 case glslang::EOpSubgroupExclusiveAnd:
5532 case glslang::EOpSubgroupExclusiveOr:
5533 case glslang::EOpSubgroupExclusiveXor:
5534 case glslang::EOpSubgroupQuadSwapHorizontal:
5535 case glslang::EOpSubgroupQuadSwapVertical:
5536 case glslang::EOpSubgroupQuadSwapDiagonal: {
5537 std::vector<spv::Id> operands;
5538 operands.push_back(operand);
5539 return createSubgroupOperation(op, typeId, operands, typeProxy);
5540 }
Rex Xu9d93a232016-05-05 12:30:44 +08005541#ifdef AMD_EXTENSIONS
5542 case glslang::EOpMbcnt:
5543 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5544 libCall = spv::MbcntAMD;
5545 break;
5546
5547 case glslang::EOpCubeFaceIndex:
5548 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5549 libCall = spv::CubeFaceIndexAMD;
5550 break;
5551
5552 case glslang::EOpCubeFaceCoord:
5553 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5554 libCall = spv::CubeFaceCoordAMD;
5555 break;
5556#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005557#ifdef NV_EXTENSIONS
5558 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005559 unaryOp = spv::OpGroupNonUniformPartitionNV;
5560 break;
5561#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005562 case glslang::EOpConstructReference:
5563 unaryOp = spv::OpBitcast;
5564 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005565
5566 case glslang::EOpCopyObject:
5567 unaryOp = spv::OpCopyObject;
5568 break;
5569
John Kessenich140f3df2015-06-26 16:58:36 -06005570 default:
5571 return 0;
5572 }
5573
5574 spv::Id id;
5575 if (libCall >= 0) {
5576 std::vector<spv::Id> args;
5577 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005578 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005579 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005580 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005581 }
John Kessenich140f3df2015-06-26 16:58:36 -06005582
John Kessenichead86222018-03-28 18:01:20 -06005583 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005584 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005585 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005586}
5587
John Kessenich7a53f762016-01-20 11:19:27 -07005588// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005589spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5590 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005591{
5592 // Handle unary operations vector by vector.
5593 // The result type is the same type as the original type.
5594 // The algorithm is to:
5595 // - break the matrix into vectors
5596 // - apply the operation to each vector
5597 // - make a matrix out the vector results
5598
5599 // get the types sorted out
5600 int numCols = builder.getNumColumns(operand);
5601 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005602 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5603 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005604 std::vector<spv::Id> results;
5605
5606 // do each vector op
5607 for (int c = 0; c < numCols; ++c) {
5608 std::vector<unsigned int> indexes;
5609 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005610 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5611 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005612 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005613 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005614 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005615 }
5616
5617 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005618 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005619 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005620 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005621}
5622
John Kessenichad7645f2018-06-04 19:11:25 -06005623// For converting integers where both the bitwidth and the signedness could
5624// change, but only do the width change here. The caller is still responsible
5625// for the signedness conversion.
5626spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005627{
John Kessenichad7645f2018-06-04 19:11:25 -06005628 // Get the result type width, based on the type to convert to.
5629 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005630 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005631 case glslang::EOpConvInt16ToUint8:
5632 case glslang::EOpConvIntToUint8:
5633 case glslang::EOpConvInt64ToUint8:
5634 case glslang::EOpConvUint16ToInt8:
5635 case glslang::EOpConvUintToInt8:
5636 case glslang::EOpConvUint64ToInt8:
5637 width = 8;
5638 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005639 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005640 case glslang::EOpConvIntToUint16:
5641 case glslang::EOpConvInt64ToUint16:
5642 case glslang::EOpConvUint8ToInt16:
5643 case glslang::EOpConvUintToInt16:
5644 case glslang::EOpConvUint64ToInt16:
5645 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005646 break;
5647 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005648 case glslang::EOpConvInt16ToUint:
5649 case glslang::EOpConvInt64ToUint:
5650 case glslang::EOpConvUint8ToInt:
5651 case glslang::EOpConvUint16ToInt:
5652 case glslang::EOpConvUint64ToInt:
5653 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005654 break;
5655 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005656 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005657 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005658 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005659 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005660 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005661 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005662 break;
5663
5664 default:
5665 assert(false && "Default missing");
5666 break;
5667 }
5668
John Kessenichad7645f2018-06-04 19:11:25 -06005669 // Get the conversion operation and result type,
5670 // based on the target width, but the source type.
5671 spv::Id type = spv::NoType;
5672 spv::Op convOp = spv::OpNop;
5673 switch(op) {
5674 case glslang::EOpConvInt8ToUint16:
5675 case glslang::EOpConvInt8ToUint:
5676 case glslang::EOpConvInt8ToUint64:
5677 case glslang::EOpConvInt16ToUint8:
5678 case glslang::EOpConvInt16ToUint:
5679 case glslang::EOpConvInt16ToUint64:
5680 case glslang::EOpConvIntToUint8:
5681 case glslang::EOpConvIntToUint16:
5682 case glslang::EOpConvIntToUint64:
5683 case glslang::EOpConvInt64ToUint8:
5684 case glslang::EOpConvInt64ToUint16:
5685 case glslang::EOpConvInt64ToUint:
5686 convOp = spv::OpSConvert;
5687 type = builder.makeIntType(width);
5688 break;
5689 default:
5690 convOp = spv::OpUConvert;
5691 type = builder.makeUintType(width);
5692 break;
5693 }
5694
John Kessenich66011cb2018-03-06 16:12:04 -07005695 if (vectorSize > 0)
5696 type = builder.makeVectorType(type, vectorSize);
5697
John Kessenichad7645f2018-06-04 19:11:25 -06005698 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005699}
5700
John Kessenichead86222018-03-28 18:01:20 -06005701spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5702 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005703{
5704 spv::Op convOp = spv::OpNop;
5705 spv::Id zero = 0;
5706 spv::Id one = 0;
5707
5708 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5709
5710 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005711 case glslang::EOpConvInt8ToBool:
5712 case glslang::EOpConvUint8ToBool:
5713 zero = builder.makeUint8Constant(0);
5714 zero = makeSmearedConstant(zero, vectorSize);
5715 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005716 case glslang::EOpConvInt16ToBool:
5717 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005718 zero = builder.makeUint16Constant(0);
5719 zero = makeSmearedConstant(zero, vectorSize);
5720 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5721 case glslang::EOpConvIntToBool:
5722 case glslang::EOpConvUintToBool:
5723 zero = builder.makeUintConstant(0);
5724 zero = makeSmearedConstant(zero, vectorSize);
5725 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5726 case glslang::EOpConvInt64ToBool:
5727 case glslang::EOpConvUint64ToBool:
5728 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005729 zero = makeSmearedConstant(zero, vectorSize);
5730 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5731
5732 case glslang::EOpConvFloatToBool:
5733 zero = builder.makeFloatConstant(0.0F);
5734 zero = makeSmearedConstant(zero, vectorSize);
5735 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5736
5737 case glslang::EOpConvDoubleToBool:
5738 zero = builder.makeDoubleConstant(0.0);
5739 zero = makeSmearedConstant(zero, vectorSize);
5740 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5741
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005742 case glslang::EOpConvFloat16ToBool:
5743 zero = builder.makeFloat16Constant(0.0F);
5744 zero = makeSmearedConstant(zero, vectorSize);
5745 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005746
John Kessenich140f3df2015-06-26 16:58:36 -06005747 case glslang::EOpConvBoolToFloat:
5748 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005749 zero = builder.makeFloatConstant(0.0F);
5750 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005751 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005752
John Kessenich140f3df2015-06-26 16:58:36 -06005753 case glslang::EOpConvBoolToDouble:
5754 convOp = spv::OpSelect;
5755 zero = builder.makeDoubleConstant(0.0);
5756 one = builder.makeDoubleConstant(1.0);
5757 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005758
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005759 case glslang::EOpConvBoolToFloat16:
5760 convOp = spv::OpSelect;
5761 zero = builder.makeFloat16Constant(0.0F);
5762 one = builder.makeFloat16Constant(1.0F);
5763 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005764
5765 case glslang::EOpConvBoolToInt8:
5766 zero = builder.makeInt8Constant(0);
5767 one = builder.makeInt8Constant(1);
5768 convOp = spv::OpSelect;
5769 break;
5770
5771 case glslang::EOpConvBoolToUint8:
5772 zero = builder.makeUint8Constant(0);
5773 one = builder.makeUint8Constant(1);
5774 convOp = spv::OpSelect;
5775 break;
5776
5777 case glslang::EOpConvBoolToInt16:
5778 zero = builder.makeInt16Constant(0);
5779 one = builder.makeInt16Constant(1);
5780 convOp = spv::OpSelect;
5781 break;
5782
5783 case glslang::EOpConvBoolToUint16:
5784 zero = builder.makeUint16Constant(0);
5785 one = builder.makeUint16Constant(1);
5786 convOp = spv::OpSelect;
5787 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005788
John Kessenich140f3df2015-06-26 16:58:36 -06005789 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005790 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005791 if (op == glslang::EOpConvBoolToInt64)
5792 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005793 else
5794 zero = builder.makeIntConstant(0);
5795
5796 if (op == glslang::EOpConvBoolToInt64)
5797 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005798 else
5799 one = builder.makeIntConstant(1);
5800
John Kessenich140f3df2015-06-26 16:58:36 -06005801 convOp = spv::OpSelect;
5802 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005803
John Kessenich140f3df2015-06-26 16:58:36 -06005804 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005805 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005806 if (op == glslang::EOpConvBoolToUint64)
5807 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005808 else
5809 zero = builder.makeUintConstant(0);
5810
5811 if (op == glslang::EOpConvBoolToUint64)
5812 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005813 else
5814 one = builder.makeUintConstant(1);
5815
John Kessenich140f3df2015-06-26 16:58:36 -06005816 convOp = spv::OpSelect;
5817 break;
5818
John Kessenich66011cb2018-03-06 16:12:04 -07005819 case glslang::EOpConvInt8ToFloat16:
5820 case glslang::EOpConvInt8ToFloat:
5821 case glslang::EOpConvInt8ToDouble:
5822 case glslang::EOpConvInt16ToFloat16:
5823 case glslang::EOpConvInt16ToFloat:
5824 case glslang::EOpConvInt16ToDouble:
5825 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005826 case glslang::EOpConvIntToFloat:
5827 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005828 case glslang::EOpConvInt64ToFloat:
5829 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005830 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005831 convOp = spv::OpConvertSToF;
5832 break;
5833
John Kessenich66011cb2018-03-06 16:12:04 -07005834 case glslang::EOpConvUint8ToFloat16:
5835 case glslang::EOpConvUint8ToFloat:
5836 case glslang::EOpConvUint8ToDouble:
5837 case glslang::EOpConvUint16ToFloat16:
5838 case glslang::EOpConvUint16ToFloat:
5839 case glslang::EOpConvUint16ToDouble:
5840 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005841 case glslang::EOpConvUintToFloat:
5842 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005843 case glslang::EOpConvUint64ToFloat:
5844 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005845 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005846 convOp = spv::OpConvertUToF;
5847 break;
5848
5849 case glslang::EOpConvDoubleToFloat:
5850 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005851 case glslang::EOpConvDoubleToFloat16:
5852 case glslang::EOpConvFloat16ToDouble:
5853 case glslang::EOpConvFloatToFloat16:
5854 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005855 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005856 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005857 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859
John Kessenich66011cb2018-03-06 16:12:04 -07005860 case glslang::EOpConvFloat16ToInt8:
5861 case glslang::EOpConvFloatToInt8:
5862 case glslang::EOpConvDoubleToInt8:
5863 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005864 case glslang::EOpConvFloatToInt16:
5865 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005866 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005867 case glslang::EOpConvFloatToInt:
5868 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005869 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005870 case glslang::EOpConvFloatToInt64:
5871 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005872 convOp = spv::OpConvertFToS;
5873 break;
5874
John Kessenich66011cb2018-03-06 16:12:04 -07005875 case glslang::EOpConvUint8ToInt8:
5876 case glslang::EOpConvInt8ToUint8:
5877 case glslang::EOpConvUint16ToInt16:
5878 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005879 case glslang::EOpConvUintToInt:
5880 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005881 case glslang::EOpConvUint64ToInt64:
5882 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005883 if (builder.isInSpecConstCodeGenMode()) {
5884 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005885 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5886 zero = builder.makeUint8Constant(0);
5887 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005888 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005889 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5890 zero = builder.makeUint64Constant(0);
5891 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005892 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005893 }
qining189b2032016-04-12 23:16:20 -04005894 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005895 // Use OpIAdd, instead of OpBitcast to do the conversion when
5896 // generating for OpSpecConstantOp instruction.
5897 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5898 }
5899 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005900 convOp = spv::OpBitcast;
5901 break;
5902
John Kessenich66011cb2018-03-06 16:12:04 -07005903 case glslang::EOpConvFloat16ToUint8:
5904 case glslang::EOpConvFloatToUint8:
5905 case glslang::EOpConvDoubleToUint8:
5906 case glslang::EOpConvFloat16ToUint16:
5907 case glslang::EOpConvFloatToUint16:
5908 case glslang::EOpConvDoubleToUint16:
5909 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005910 case glslang::EOpConvFloatToUint:
5911 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005912 case glslang::EOpConvFloatToUint64:
5913 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005914 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005915 convOp = spv::OpConvertFToU;
5916 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005917
John Kessenich66011cb2018-03-06 16:12:04 -07005918 case glslang::EOpConvInt8ToInt16:
5919 case glslang::EOpConvInt8ToInt:
5920 case glslang::EOpConvInt8ToInt64:
5921 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005922 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005923 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005924 case glslang::EOpConvIntToInt8:
5925 case glslang::EOpConvIntToInt16:
5926 case glslang::EOpConvIntToInt64:
5927 case glslang::EOpConvInt64ToInt8:
5928 case glslang::EOpConvInt64ToInt16:
5929 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005930 convOp = spv::OpSConvert;
5931 break;
5932
John Kessenich66011cb2018-03-06 16:12:04 -07005933 case glslang::EOpConvUint8ToUint16:
5934 case glslang::EOpConvUint8ToUint:
5935 case glslang::EOpConvUint8ToUint64:
5936 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005937 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005938 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005939 case glslang::EOpConvUintToUint8:
5940 case glslang::EOpConvUintToUint16:
5941 case glslang::EOpConvUintToUint64:
5942 case glslang::EOpConvUint64ToUint8:
5943 case glslang::EOpConvUint64ToUint16:
5944 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005945 convOp = spv::OpUConvert;
5946 break;
5947
John Kessenich66011cb2018-03-06 16:12:04 -07005948 case glslang::EOpConvInt8ToUint16:
5949 case glslang::EOpConvInt8ToUint:
5950 case glslang::EOpConvInt8ToUint64:
5951 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005952 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005953 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005954 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005955 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005956 case glslang::EOpConvIntToUint64:
5957 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005958 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005959 case glslang::EOpConvInt64ToUint:
5960 case glslang::EOpConvUint8ToInt16:
5961 case glslang::EOpConvUint8ToInt:
5962 case glslang::EOpConvUint8ToInt64:
5963 case glslang::EOpConvUint16ToInt8:
5964 case glslang::EOpConvUint16ToInt:
5965 case glslang::EOpConvUint16ToInt64:
5966 case glslang::EOpConvUintToInt8:
5967 case glslang::EOpConvUintToInt16:
5968 case glslang::EOpConvUintToInt64:
5969 case glslang::EOpConvUint64ToInt8:
5970 case glslang::EOpConvUint64ToInt16:
5971 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005972 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005973 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005974
5975 if (builder.isInSpecConstCodeGenMode()) {
5976 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005977 switch(op) {
5978 case glslang::EOpConvInt16ToUint8:
5979 case glslang::EOpConvIntToUint8:
5980 case glslang::EOpConvInt64ToUint8:
5981 case glslang::EOpConvUint16ToInt8:
5982 case glslang::EOpConvUintToInt8:
5983 case glslang::EOpConvUint64ToInt8:
5984 zero = builder.makeUint8Constant(0);
5985 break;
5986 case glslang::EOpConvInt8ToUint16:
5987 case glslang::EOpConvIntToUint16:
5988 case glslang::EOpConvInt64ToUint16:
5989 case glslang::EOpConvUint8ToInt16:
5990 case glslang::EOpConvUintToInt16:
5991 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005992 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005993 break;
5994 case glslang::EOpConvInt8ToUint:
5995 case glslang::EOpConvInt16ToUint:
5996 case glslang::EOpConvInt64ToUint:
5997 case glslang::EOpConvUint8ToInt:
5998 case glslang::EOpConvUint16ToInt:
5999 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006000 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006001 break;
6002 case glslang::EOpConvInt8ToUint64:
6003 case glslang::EOpConvInt16ToUint64:
6004 case glslang::EOpConvIntToUint64:
6005 case glslang::EOpConvUint8ToInt64:
6006 case glslang::EOpConvUint16ToInt64:
6007 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006008 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006009 break;
6010 default:
6011 assert(false && "Default missing");
6012 break;
6013 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006014 zero = makeSmearedConstant(zero, vectorSize);
6015 // Use OpIAdd, instead of OpBitcast to do the conversion when
6016 // generating for OpSpecConstantOp instruction.
6017 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6018 }
6019 // For normal run-time conversion instruction, use OpBitcast.
6020 convOp = spv::OpBitcast;
6021 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006022 case glslang::EOpConvUint64ToPtr:
6023 convOp = spv::OpConvertUToPtr;
6024 break;
6025 case glslang::EOpConvPtrToUint64:
6026 convOp = spv::OpConvertPtrToU;
6027 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006028 default:
6029 break;
6030 }
6031
6032 spv::Id result = 0;
6033 if (convOp == spv::OpNop)
6034 return result;
6035
6036 if (convOp == spv::OpSelect) {
6037 zero = makeSmearedConstant(zero, vectorSize);
6038 one = makeSmearedConstant(one, vectorSize);
6039 result = builder.createTriOp(convOp, destType, operand, one, zero);
6040 } else
6041 result = builder.createUnaryOp(convOp, destType, operand);
6042
John Kessenichead86222018-03-28 18:01:20 -06006043 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006044 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006045 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006046}
6047
6048spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6049{
6050 if (vectorSize == 0)
6051 return constant;
6052
6053 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6054 std::vector<spv::Id> components;
6055 for (int c = 0; c < vectorSize; ++c)
6056 components.push_back(constant);
6057 return builder.makeCompositeConstant(vectorTypeId, components);
6058}
6059
John Kessenich426394d2015-07-23 10:22:48 -06006060// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006061spv::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 -06006062{
6063 spv::Op opCode = spv::OpNop;
6064
6065 switch (op) {
6066 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006067 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006068 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006069 opCode = spv::OpAtomicIAdd;
6070 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006071 case glslang::EOpAtomicCounterSubtract:
6072 opCode = spv::OpAtomicISub;
6073 break;
John Kessenich426394d2015-07-23 10:22:48 -06006074 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006075 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006076 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006077 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006078 break;
6079 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006080 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006081 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006082 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006083 break;
6084 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006085 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006086 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006087 opCode = spv::OpAtomicAnd;
6088 break;
6089 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006090 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006091 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006092 opCode = spv::OpAtomicOr;
6093 break;
6094 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006095 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006096 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006097 opCode = spv::OpAtomicXor;
6098 break;
6099 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006100 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006101 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006102 opCode = spv::OpAtomicExchange;
6103 break;
6104 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006105 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006106 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006107 opCode = spv::OpAtomicCompareExchange;
6108 break;
6109 case glslang::EOpAtomicCounterIncrement:
6110 opCode = spv::OpAtomicIIncrement;
6111 break;
6112 case glslang::EOpAtomicCounterDecrement:
6113 opCode = spv::OpAtomicIDecrement;
6114 break;
6115 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006116 case glslang::EOpImageAtomicLoad:
6117 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006118 opCode = spv::OpAtomicLoad;
6119 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006120 case glslang::EOpAtomicStore:
6121 case glslang::EOpImageAtomicStore:
6122 opCode = spv::OpAtomicStore;
6123 break;
John Kessenich426394d2015-07-23 10:22:48 -06006124 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006125 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006126 break;
6127 }
6128
Rex Xue8fe8b02017-09-26 15:42:56 +08006129 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6130 builder.addCapability(spv::CapabilityInt64Atomics);
6131
John Kessenich426394d2015-07-23 10:22:48 -06006132 // Sort out the operands
6133 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006134 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006135 // - compare-exchange swaps the value and comparator
6136 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006137 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006138 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6139 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6140 spv::Id scopeId;
6141 if (glslangIntermediate->usingVulkanMemoryModel()) {
6142 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6143 } else {
6144 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6145 }
6146 // semantics default to relaxed
6147 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6148 spv::Id semanticsId2 = semanticsId;
6149
6150 pointerId = operands[0];
6151 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6152 // no additional operands
6153 } else if (opCode == spv::OpAtomicCompareExchange) {
6154 compareId = operands[1];
6155 valueId = operands[2];
6156 if (operands.size() > 3) {
6157 scopeId = operands[3];
6158 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6159 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6160 }
6161 } else if (opCode == spv::OpAtomicLoad) {
6162 if (operands.size() > 1) {
6163 scopeId = operands[1];
6164 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6165 }
6166 } else {
6167 // atomic store or RMW
6168 valueId = operands[1];
6169 if (operands.size() > 2) {
6170 scopeId = operands[2];
6171 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6172 }
Rex Xu04db3f52015-09-16 11:44:02 +08006173 }
John Kessenich426394d2015-07-23 10:22:48 -06006174
Jeff Bolz36831c92018-09-05 10:11:41 -05006175 // Check for capabilities
6176 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6177 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6178 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6179 }
John Kessenich426394d2015-07-23 10:22:48 -06006180
Jeff Bolz36831c92018-09-05 10:11:41 -05006181 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6182 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6183 }
John Kessenich48d6e792017-10-06 21:21:48 -06006184
Jeff Bolz36831c92018-09-05 10:11:41 -05006185 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6186 spvAtomicOperands.push_back(pointerId);
6187 spvAtomicOperands.push_back(scopeId);
6188 spvAtomicOperands.push_back(semanticsId);
6189 if (opCode == spv::OpAtomicCompareExchange) {
6190 spvAtomicOperands.push_back(semanticsId2);
6191 spvAtomicOperands.push_back(valueId);
6192 spvAtomicOperands.push_back(compareId);
6193 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6194 spvAtomicOperands.push_back(valueId);
6195 }
John Kessenich48d6e792017-10-06 21:21:48 -06006196
Jeff Bolz36831c92018-09-05 10:11:41 -05006197 if (opCode == spv::OpAtomicStore) {
6198 builder.createNoResultOp(opCode, spvAtomicOperands);
6199 return 0;
6200 } else {
6201 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6202
6203 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6204 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6205 if (op == glslang::EOpAtomicCounterDecrement)
6206 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6207
6208 return resultId;
6209 }
John Kessenich426394d2015-07-23 10:22:48 -06006210}
6211
John Kessenich91cef522016-05-05 16:45:40 -06006212// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006213spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006214{
Corentin Walleze7061422018-08-08 15:20:15 +02006215#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006216 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6217 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006218#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006219
Rex Xu51596642016-09-21 18:56:12 +08006220 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006221 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006222 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6223
chaocf200da82016-12-20 12:44:35 -08006224 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6225 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006226 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6227 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006228 } else if (op == glslang::EOpAnyInvocation ||
6229 op == glslang::EOpAllInvocations ||
6230 op == glslang::EOpAllInvocationsEqual) {
6231 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6232 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006233 } else {
6234 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006235#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006236 if (op == glslang::EOpMinInvocationsNonUniform ||
6237 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006238 op == glslang::EOpAddInvocationsNonUniform ||
6239 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6240 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6241 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6242 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6243 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6244 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006245 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006246#endif
Rex Xu51596642016-09-21 18:56:12 +08006247
Rex Xu9d93a232016-05-05 12:30:44 +08006248#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006249 switch (op) {
6250 case glslang::EOpMinInvocations:
6251 case glslang::EOpMaxInvocations:
6252 case glslang::EOpAddInvocations:
6253 case glslang::EOpMinInvocationsNonUniform:
6254 case glslang::EOpMaxInvocationsNonUniform:
6255 case glslang::EOpAddInvocationsNonUniform:
6256 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006257 break;
6258 case glslang::EOpMinInvocationsInclusiveScan:
6259 case glslang::EOpMaxInvocationsInclusiveScan:
6260 case glslang::EOpAddInvocationsInclusiveScan:
6261 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6262 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6263 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6264 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006265 break;
6266 case glslang::EOpMinInvocationsExclusiveScan:
6267 case glslang::EOpMaxInvocationsExclusiveScan:
6268 case glslang::EOpAddInvocationsExclusiveScan:
6269 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6270 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6271 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6272 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006273 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006274 default:
6275 break;
Rex Xu430ef402016-10-14 17:22:23 +08006276 }
John Kessenich149afc32018-08-14 13:31:43 -06006277 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6278 spvGroupOperands.push_back(scope);
6279 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006280 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006281 spvGroupOperands.push_back(groupOp);
6282 }
Rex Xu9d93a232016-05-05 12:30:44 +08006283#endif
Rex Xu51596642016-09-21 18:56:12 +08006284 }
6285
John Kessenich149afc32018-08-14 13:31:43 -06006286 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6287 spv::IdImmediate op = { true, *opIt };
6288 spvGroupOperands.push_back(op);
6289 }
John Kessenich91cef522016-05-05 16:45:40 -06006290
6291 switch (op) {
6292 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006293 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006294 break;
John Kessenich91cef522016-05-05 16:45:40 -06006295 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006296 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006297 break;
John Kessenich91cef522016-05-05 16:45:40 -06006298 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006299 opCode = spv::OpSubgroupAllEqualKHR;
6300 break;
Rex Xu51596642016-09-21 18:56:12 +08006301 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006302 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006303 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006304 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006305 break;
6306 case glslang::EOpReadFirstInvocation:
6307 opCode = spv::OpSubgroupFirstInvocationKHR;
6308 break;
6309 case glslang::EOpBallot:
6310 {
6311 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6312 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6313 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6314 //
6315 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6316 //
6317 spv::Id uintType = builder.makeUintType(32);
6318 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6319 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6320
6321 std::vector<spv::Id> components;
6322 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6323 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6324
6325 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6326 return builder.createUnaryOp(spv::OpBitcast, typeId,
6327 builder.createCompositeConstruct(uvec2Type, components));
6328 }
6329
Rex Xu9d93a232016-05-05 12:30:44 +08006330#ifdef AMD_EXTENSIONS
6331 case glslang::EOpMinInvocations:
6332 case glslang::EOpMaxInvocations:
6333 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006334 case glslang::EOpMinInvocationsInclusiveScan:
6335 case glslang::EOpMaxInvocationsInclusiveScan:
6336 case glslang::EOpAddInvocationsInclusiveScan:
6337 case glslang::EOpMinInvocationsExclusiveScan:
6338 case glslang::EOpMaxInvocationsExclusiveScan:
6339 case glslang::EOpAddInvocationsExclusiveScan:
6340 if (op == glslang::EOpMinInvocations ||
6341 op == glslang::EOpMinInvocationsInclusiveScan ||
6342 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006343 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006344 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006345 else {
6346 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006347 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006348 else
Rex Xu51596642016-09-21 18:56:12 +08006349 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006350 }
Rex Xu430ef402016-10-14 17:22:23 +08006351 } else if (op == glslang::EOpMaxInvocations ||
6352 op == glslang::EOpMaxInvocationsInclusiveScan ||
6353 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006354 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006355 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006356 else {
6357 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006358 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006359 else
Rex Xu51596642016-09-21 18:56:12 +08006360 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006361 }
6362 } else {
6363 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006364 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006365 else
Rex Xu51596642016-09-21 18:56:12 +08006366 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006367 }
6368
Rex Xu2bbbe062016-08-23 15:41:05 +08006369 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006370 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006371
6372 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006373 case glslang::EOpMinInvocationsNonUniform:
6374 case glslang::EOpMaxInvocationsNonUniform:
6375 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006376 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6377 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6378 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6379 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6380 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6381 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6382 if (op == glslang::EOpMinInvocationsNonUniform ||
6383 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6384 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006385 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006386 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006387 else {
6388 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006389 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006390 else
Rex Xu51596642016-09-21 18:56:12 +08006391 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006392 }
6393 }
Rex Xu430ef402016-10-14 17:22:23 +08006394 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6395 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6396 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006397 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006398 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006399 else {
6400 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006401 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006402 else
Rex Xu51596642016-09-21 18:56:12 +08006403 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006404 }
6405 }
6406 else {
6407 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006408 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006409 else
Rex Xu51596642016-09-21 18:56:12 +08006410 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006411 }
6412
Rex Xu2bbbe062016-08-23 15:41:05 +08006413 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006414 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006415
6416 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006417#endif
John Kessenich91cef522016-05-05 16:45:40 -06006418 default:
6419 logger->missingFunctionality("invocation operation");
6420 return spv::NoResult;
6421 }
Rex Xu51596642016-09-21 18:56:12 +08006422
6423 assert(opCode != spv::OpNop);
6424 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006425}
6426
Rex Xu2bbbe062016-08-23 15:41:05 +08006427// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006428spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6429 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006430{
Rex Xub7072052016-09-26 15:53:40 +08006431#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006432 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6433 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006434 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006435 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006436 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6437 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6438 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006439#else
6440 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6441 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006442 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6443 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006444#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006445
6446 // Handle group invocation operations scalar by scalar.
6447 // The result type is the same type as the original type.
6448 // The algorithm is to:
6449 // - break the vector into scalars
6450 // - apply the operation to each scalar
6451 // - make a vector out the scalar results
6452
6453 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006454 int numComponents = builder.getNumComponents(operands[0]);
6455 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006456 std::vector<spv::Id> results;
6457
6458 // do each scalar op
6459 for (int comp = 0; comp < numComponents; ++comp) {
6460 std::vector<unsigned int> indexes;
6461 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006462 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6463 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006464 if (op == spv::OpSubgroupReadInvocationKHR) {
6465 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006466 spv::IdImmediate operand = { true, operands[1] };
6467 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006468 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006469 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6470 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006471 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006472 spv::IdImmediate operand = { true, operands[1] };
6473 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006474 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006475 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6476 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006477 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006478 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006479 spvGroupOperands.push_back(scalar);
6480 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006481
Rex Xub7072052016-09-26 15:53:40 +08006482 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006483 }
6484
6485 // put the pieces together
6486 return builder.createCompositeConstruct(typeId, results);
6487}
Rex Xu2bbbe062016-08-23 15:41:05 +08006488
John Kessenich66011cb2018-03-06 16:12:04 -07006489// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006490spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6491 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006492{
6493 // Add the required capabilities.
6494 switch (op) {
6495 case glslang::EOpSubgroupElect:
6496 builder.addCapability(spv::CapabilityGroupNonUniform);
6497 break;
6498 case glslang::EOpSubgroupAll:
6499 case glslang::EOpSubgroupAny:
6500 case glslang::EOpSubgroupAllEqual:
6501 builder.addCapability(spv::CapabilityGroupNonUniform);
6502 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6503 break;
6504 case glslang::EOpSubgroupBroadcast:
6505 case glslang::EOpSubgroupBroadcastFirst:
6506 case glslang::EOpSubgroupBallot:
6507 case glslang::EOpSubgroupInverseBallot:
6508 case glslang::EOpSubgroupBallotBitExtract:
6509 case glslang::EOpSubgroupBallotBitCount:
6510 case glslang::EOpSubgroupBallotInclusiveBitCount:
6511 case glslang::EOpSubgroupBallotExclusiveBitCount:
6512 case glslang::EOpSubgroupBallotFindLSB:
6513 case glslang::EOpSubgroupBallotFindMSB:
6514 builder.addCapability(spv::CapabilityGroupNonUniform);
6515 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6516 break;
6517 case glslang::EOpSubgroupShuffle:
6518 case glslang::EOpSubgroupShuffleXor:
6519 builder.addCapability(spv::CapabilityGroupNonUniform);
6520 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6521 break;
6522 case glslang::EOpSubgroupShuffleUp:
6523 case glslang::EOpSubgroupShuffleDown:
6524 builder.addCapability(spv::CapabilityGroupNonUniform);
6525 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6526 break;
6527 case glslang::EOpSubgroupAdd:
6528 case glslang::EOpSubgroupMul:
6529 case glslang::EOpSubgroupMin:
6530 case glslang::EOpSubgroupMax:
6531 case glslang::EOpSubgroupAnd:
6532 case glslang::EOpSubgroupOr:
6533 case glslang::EOpSubgroupXor:
6534 case glslang::EOpSubgroupInclusiveAdd:
6535 case glslang::EOpSubgroupInclusiveMul:
6536 case glslang::EOpSubgroupInclusiveMin:
6537 case glslang::EOpSubgroupInclusiveMax:
6538 case glslang::EOpSubgroupInclusiveAnd:
6539 case glslang::EOpSubgroupInclusiveOr:
6540 case glslang::EOpSubgroupInclusiveXor:
6541 case glslang::EOpSubgroupExclusiveAdd:
6542 case glslang::EOpSubgroupExclusiveMul:
6543 case glslang::EOpSubgroupExclusiveMin:
6544 case glslang::EOpSubgroupExclusiveMax:
6545 case glslang::EOpSubgroupExclusiveAnd:
6546 case glslang::EOpSubgroupExclusiveOr:
6547 case glslang::EOpSubgroupExclusiveXor:
6548 builder.addCapability(spv::CapabilityGroupNonUniform);
6549 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6550 break;
6551 case glslang::EOpSubgroupClusteredAdd:
6552 case glslang::EOpSubgroupClusteredMul:
6553 case glslang::EOpSubgroupClusteredMin:
6554 case glslang::EOpSubgroupClusteredMax:
6555 case glslang::EOpSubgroupClusteredAnd:
6556 case glslang::EOpSubgroupClusteredOr:
6557 case glslang::EOpSubgroupClusteredXor:
6558 builder.addCapability(spv::CapabilityGroupNonUniform);
6559 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6560 break;
6561 case glslang::EOpSubgroupQuadBroadcast:
6562 case glslang::EOpSubgroupQuadSwapHorizontal:
6563 case glslang::EOpSubgroupQuadSwapVertical:
6564 case glslang::EOpSubgroupQuadSwapDiagonal:
6565 builder.addCapability(spv::CapabilityGroupNonUniform);
6566 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6567 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006568#ifdef NV_EXTENSIONS
6569 case glslang::EOpSubgroupPartitionedAdd:
6570 case glslang::EOpSubgroupPartitionedMul:
6571 case glslang::EOpSubgroupPartitionedMin:
6572 case glslang::EOpSubgroupPartitionedMax:
6573 case glslang::EOpSubgroupPartitionedAnd:
6574 case glslang::EOpSubgroupPartitionedOr:
6575 case glslang::EOpSubgroupPartitionedXor:
6576 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6577 case glslang::EOpSubgroupPartitionedInclusiveMul:
6578 case glslang::EOpSubgroupPartitionedInclusiveMin:
6579 case glslang::EOpSubgroupPartitionedInclusiveMax:
6580 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6581 case glslang::EOpSubgroupPartitionedInclusiveOr:
6582 case glslang::EOpSubgroupPartitionedInclusiveXor:
6583 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6584 case glslang::EOpSubgroupPartitionedExclusiveMul:
6585 case glslang::EOpSubgroupPartitionedExclusiveMin:
6586 case glslang::EOpSubgroupPartitionedExclusiveMax:
6587 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6588 case glslang::EOpSubgroupPartitionedExclusiveOr:
6589 case glslang::EOpSubgroupPartitionedExclusiveXor:
6590 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6591 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6592 break;
6593#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006594 default: assert(0 && "Unhandled subgroup operation!");
6595 }
6596
6597 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6598 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6599 const bool isBool = typeProxy == glslang::EbtBool;
6600
6601 spv::Op opCode = spv::OpNop;
6602
6603 // Figure out which opcode to use.
6604 switch (op) {
6605 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6606 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6607 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6608 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6609 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6610 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6611 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6612 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6613 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6614 case glslang::EOpSubgroupBallotBitCount:
6615 case glslang::EOpSubgroupBallotInclusiveBitCount:
6616 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6617 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6618 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6619 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6620 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6621 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6622 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6623 case glslang::EOpSubgroupAdd:
6624 case glslang::EOpSubgroupInclusiveAdd:
6625 case glslang::EOpSubgroupExclusiveAdd:
6626 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006627#ifdef NV_EXTENSIONS
6628 case glslang::EOpSubgroupPartitionedAdd:
6629 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6630 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6631#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006632 if (isFloat) {
6633 opCode = spv::OpGroupNonUniformFAdd;
6634 } else {
6635 opCode = spv::OpGroupNonUniformIAdd;
6636 }
6637 break;
6638 case glslang::EOpSubgroupMul:
6639 case glslang::EOpSubgroupInclusiveMul:
6640 case glslang::EOpSubgroupExclusiveMul:
6641 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006642#ifdef NV_EXTENSIONS
6643 case glslang::EOpSubgroupPartitionedMul:
6644 case glslang::EOpSubgroupPartitionedInclusiveMul:
6645 case glslang::EOpSubgroupPartitionedExclusiveMul:
6646#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006647 if (isFloat) {
6648 opCode = spv::OpGroupNonUniformFMul;
6649 } else {
6650 opCode = spv::OpGroupNonUniformIMul;
6651 }
6652 break;
6653 case glslang::EOpSubgroupMin:
6654 case glslang::EOpSubgroupInclusiveMin:
6655 case glslang::EOpSubgroupExclusiveMin:
6656 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006657#ifdef NV_EXTENSIONS
6658 case glslang::EOpSubgroupPartitionedMin:
6659 case glslang::EOpSubgroupPartitionedInclusiveMin:
6660 case glslang::EOpSubgroupPartitionedExclusiveMin:
6661#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006662 if (isFloat) {
6663 opCode = spv::OpGroupNonUniformFMin;
6664 } else if (isUnsigned) {
6665 opCode = spv::OpGroupNonUniformUMin;
6666 } else {
6667 opCode = spv::OpGroupNonUniformSMin;
6668 }
6669 break;
6670 case glslang::EOpSubgroupMax:
6671 case glslang::EOpSubgroupInclusiveMax:
6672 case glslang::EOpSubgroupExclusiveMax:
6673 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006674#ifdef NV_EXTENSIONS
6675 case glslang::EOpSubgroupPartitionedMax:
6676 case glslang::EOpSubgroupPartitionedInclusiveMax:
6677 case glslang::EOpSubgroupPartitionedExclusiveMax:
6678#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006679 if (isFloat) {
6680 opCode = spv::OpGroupNonUniformFMax;
6681 } else if (isUnsigned) {
6682 opCode = spv::OpGroupNonUniformUMax;
6683 } else {
6684 opCode = spv::OpGroupNonUniformSMax;
6685 }
6686 break;
6687 case glslang::EOpSubgroupAnd:
6688 case glslang::EOpSubgroupInclusiveAnd:
6689 case glslang::EOpSubgroupExclusiveAnd:
6690 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006691#ifdef NV_EXTENSIONS
6692 case glslang::EOpSubgroupPartitionedAnd:
6693 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6694 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6695#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006696 if (isBool) {
6697 opCode = spv::OpGroupNonUniformLogicalAnd;
6698 } else {
6699 opCode = spv::OpGroupNonUniformBitwiseAnd;
6700 }
6701 break;
6702 case glslang::EOpSubgroupOr:
6703 case glslang::EOpSubgroupInclusiveOr:
6704 case glslang::EOpSubgroupExclusiveOr:
6705 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006706#ifdef NV_EXTENSIONS
6707 case glslang::EOpSubgroupPartitionedOr:
6708 case glslang::EOpSubgroupPartitionedInclusiveOr:
6709 case glslang::EOpSubgroupPartitionedExclusiveOr:
6710#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006711 if (isBool) {
6712 opCode = spv::OpGroupNonUniformLogicalOr;
6713 } else {
6714 opCode = spv::OpGroupNonUniformBitwiseOr;
6715 }
6716 break;
6717 case glslang::EOpSubgroupXor:
6718 case glslang::EOpSubgroupInclusiveXor:
6719 case glslang::EOpSubgroupExclusiveXor:
6720 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006721#ifdef NV_EXTENSIONS
6722 case glslang::EOpSubgroupPartitionedXor:
6723 case glslang::EOpSubgroupPartitionedInclusiveXor:
6724 case glslang::EOpSubgroupPartitionedExclusiveXor:
6725#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006726 if (isBool) {
6727 opCode = spv::OpGroupNonUniformLogicalXor;
6728 } else {
6729 opCode = spv::OpGroupNonUniformBitwiseXor;
6730 }
6731 break;
6732 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6733 case glslang::EOpSubgroupQuadSwapHorizontal:
6734 case glslang::EOpSubgroupQuadSwapVertical:
6735 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6736 default: assert(0 && "Unhandled subgroup operation!");
6737 }
6738
John Kessenich149afc32018-08-14 13:31:43 -06006739 // get the right Group Operation
6740 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006741 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006742 default:
6743 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006744 case glslang::EOpSubgroupBallotBitCount:
6745 case glslang::EOpSubgroupAdd:
6746 case glslang::EOpSubgroupMul:
6747 case glslang::EOpSubgroupMin:
6748 case glslang::EOpSubgroupMax:
6749 case glslang::EOpSubgroupAnd:
6750 case glslang::EOpSubgroupOr:
6751 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006752 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006753 break;
6754 case glslang::EOpSubgroupBallotInclusiveBitCount:
6755 case glslang::EOpSubgroupInclusiveAdd:
6756 case glslang::EOpSubgroupInclusiveMul:
6757 case glslang::EOpSubgroupInclusiveMin:
6758 case glslang::EOpSubgroupInclusiveMax:
6759 case glslang::EOpSubgroupInclusiveAnd:
6760 case glslang::EOpSubgroupInclusiveOr:
6761 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006762 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006763 break;
6764 case glslang::EOpSubgroupBallotExclusiveBitCount:
6765 case glslang::EOpSubgroupExclusiveAdd:
6766 case glslang::EOpSubgroupExclusiveMul:
6767 case glslang::EOpSubgroupExclusiveMin:
6768 case glslang::EOpSubgroupExclusiveMax:
6769 case glslang::EOpSubgroupExclusiveAnd:
6770 case glslang::EOpSubgroupExclusiveOr:
6771 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006772 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006773 break;
6774 case glslang::EOpSubgroupClusteredAdd:
6775 case glslang::EOpSubgroupClusteredMul:
6776 case glslang::EOpSubgroupClusteredMin:
6777 case glslang::EOpSubgroupClusteredMax:
6778 case glslang::EOpSubgroupClusteredAnd:
6779 case glslang::EOpSubgroupClusteredOr:
6780 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006781 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006782 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006783#ifdef NV_EXTENSIONS
6784 case glslang::EOpSubgroupPartitionedAdd:
6785 case glslang::EOpSubgroupPartitionedMul:
6786 case glslang::EOpSubgroupPartitionedMin:
6787 case glslang::EOpSubgroupPartitionedMax:
6788 case glslang::EOpSubgroupPartitionedAnd:
6789 case glslang::EOpSubgroupPartitionedOr:
6790 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006791 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006792 break;
6793 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6794 case glslang::EOpSubgroupPartitionedInclusiveMul:
6795 case glslang::EOpSubgroupPartitionedInclusiveMin:
6796 case glslang::EOpSubgroupPartitionedInclusiveMax:
6797 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6798 case glslang::EOpSubgroupPartitionedInclusiveOr:
6799 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006800 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006801 break;
6802 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6803 case glslang::EOpSubgroupPartitionedExclusiveMul:
6804 case glslang::EOpSubgroupPartitionedExclusiveMin:
6805 case glslang::EOpSubgroupPartitionedExclusiveMax:
6806 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6807 case glslang::EOpSubgroupPartitionedExclusiveOr:
6808 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006809 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006810 break;
6811#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006812 }
6813
John Kessenich149afc32018-08-14 13:31:43 -06006814 // build the instruction
6815 std::vector<spv::IdImmediate> spvGroupOperands;
6816
6817 // Every operation begins with the Execution Scope operand.
6818 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6819 spvGroupOperands.push_back(executionScope);
6820
6821 // Next, for all operations that use a Group Operation, push that as an operand.
6822 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006823 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006824 spvGroupOperands.push_back(groupOperand);
6825 }
6826
John Kessenich66011cb2018-03-06 16:12:04 -07006827 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006828 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6829 spv::IdImmediate operand = { true, *opIt };
6830 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006831 }
6832
6833 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006834 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006835 switch (op) {
6836 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006837 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6838 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6839 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6840 }
6841 if (directionId != spv::NoResult) {
6842 spv::IdImmediate direction = { true, directionId };
6843 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006844 }
6845
6846 return builder.createOp(opCode, typeId, spvGroupOperands);
6847}
6848
John Kessenich5e4b1242015-08-06 22:53:06 -06006849spv::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 -06006850{
John Kessenich66011cb2018-03-06 16:12:04 -07006851 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6852 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006853
John Kessenich140f3df2015-06-26 16:58:36 -06006854 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006855 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006856 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006857 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006858 spv::Id typeId0 = 0;
6859 if (consumedOperands > 0)
6860 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006861 spv::Id typeId1 = 0;
6862 if (consumedOperands > 1)
6863 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006864 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006865
6866 switch (op) {
6867 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006868 if (isFloat)
6869 libCall = spv::GLSLstd450FMin;
6870 else if (isUnsigned)
6871 libCall = spv::GLSLstd450UMin;
6872 else
6873 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006874 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006875 break;
6876 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006877 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006878 break;
6879 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006880 if (isFloat)
6881 libCall = spv::GLSLstd450FMax;
6882 else if (isUnsigned)
6883 libCall = spv::GLSLstd450UMax;
6884 else
6885 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006886 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006887 break;
6888 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006889 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006890 break;
6891 case glslang::EOpDot:
6892 opCode = spv::OpDot;
6893 break;
6894 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006895 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006896 break;
6897
6898 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006899 if (isFloat)
6900 libCall = spv::GLSLstd450FClamp;
6901 else if (isUnsigned)
6902 libCall = spv::GLSLstd450UClamp;
6903 else
6904 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006905 builder.promoteScalar(precision, operands.front(), operands[1]);
6906 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006907 break;
6908 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006909 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6910 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006911 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006912 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006913 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006914 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006915 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006916 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006917 break;
6918 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006919 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006920 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006921 break;
6922 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006923 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006924 builder.promoteScalar(precision, operands[0], operands[2]);
6925 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006926 break;
6927
6928 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006929 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006930 break;
6931 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006932 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006933 break;
6934 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006935 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006936 break;
6937 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006938 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006939 break;
6940 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006941 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006942 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006943 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006944#ifdef AMD_EXTENSIONS
6945 if (typeProxy == glslang::EbtFloat16)
6946 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6947#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006948 libCall = spv::GLSLstd450InterpolateAtSample;
6949 break;
6950 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006951#ifdef AMD_EXTENSIONS
6952 if (typeProxy == glslang::EbtFloat16)
6953 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6954#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006955 libCall = spv::GLSLstd450InterpolateAtOffset;
6956 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006957 case glslang::EOpAddCarry:
6958 opCode = spv::OpIAddCarry;
6959 typeId = builder.makeStructResultType(typeId0, typeId0);
6960 consumedOperands = 2;
6961 break;
6962 case glslang::EOpSubBorrow:
6963 opCode = spv::OpISubBorrow;
6964 typeId = builder.makeStructResultType(typeId0, typeId0);
6965 consumedOperands = 2;
6966 break;
6967 case glslang::EOpUMulExtended:
6968 opCode = spv::OpUMulExtended;
6969 typeId = builder.makeStructResultType(typeId0, typeId0);
6970 consumedOperands = 2;
6971 break;
6972 case glslang::EOpIMulExtended:
6973 opCode = spv::OpSMulExtended;
6974 typeId = builder.makeStructResultType(typeId0, typeId0);
6975 consumedOperands = 2;
6976 break;
6977 case glslang::EOpBitfieldExtract:
6978 if (isUnsigned)
6979 opCode = spv::OpBitFieldUExtract;
6980 else
6981 opCode = spv::OpBitFieldSExtract;
6982 break;
6983 case glslang::EOpBitfieldInsert:
6984 opCode = spv::OpBitFieldInsert;
6985 break;
6986
6987 case glslang::EOpFma:
6988 libCall = spv::GLSLstd450Fma;
6989 break;
6990 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006991 {
6992 libCall = spv::GLSLstd450FrexpStruct;
6993 assert(builder.isPointerType(typeId1));
6994 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006995 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006996#ifdef AMD_EXTENSIONS
6997 if (width == 16)
6998 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6999 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7000#endif
Rex Xu470026f2017-03-29 17:12:40 +08007001 if (builder.getNumComponents(operands[0]) == 1)
7002 frexpIntType = builder.makeIntegerType(width, true);
7003 else
7004 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7005 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7006 consumedOperands = 1;
7007 }
John Kessenich55e7d112015-11-15 21:33:39 -07007008 break;
7009 case glslang::EOpLdexp:
7010 libCall = spv::GLSLstd450Ldexp;
7011 break;
7012
Rex Xu574ab042016-04-14 16:53:07 +08007013 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007014 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007015
John Kessenich66011cb2018-03-06 16:12:04 -07007016 case glslang::EOpSubgroupBroadcast:
7017 case glslang::EOpSubgroupBallotBitExtract:
7018 case glslang::EOpSubgroupShuffle:
7019 case glslang::EOpSubgroupShuffleXor:
7020 case glslang::EOpSubgroupShuffleUp:
7021 case glslang::EOpSubgroupShuffleDown:
7022 case glslang::EOpSubgroupClusteredAdd:
7023 case glslang::EOpSubgroupClusteredMul:
7024 case glslang::EOpSubgroupClusteredMin:
7025 case glslang::EOpSubgroupClusteredMax:
7026 case glslang::EOpSubgroupClusteredAnd:
7027 case glslang::EOpSubgroupClusteredOr:
7028 case glslang::EOpSubgroupClusteredXor:
7029 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007030#ifdef NV_EXTENSIONS
7031 case glslang::EOpSubgroupPartitionedAdd:
7032 case glslang::EOpSubgroupPartitionedMul:
7033 case glslang::EOpSubgroupPartitionedMin:
7034 case glslang::EOpSubgroupPartitionedMax:
7035 case glslang::EOpSubgroupPartitionedAnd:
7036 case glslang::EOpSubgroupPartitionedOr:
7037 case glslang::EOpSubgroupPartitionedXor:
7038 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7039 case glslang::EOpSubgroupPartitionedInclusiveMul:
7040 case glslang::EOpSubgroupPartitionedInclusiveMin:
7041 case glslang::EOpSubgroupPartitionedInclusiveMax:
7042 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7043 case glslang::EOpSubgroupPartitionedInclusiveOr:
7044 case glslang::EOpSubgroupPartitionedInclusiveXor:
7045 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7046 case glslang::EOpSubgroupPartitionedExclusiveMul:
7047 case glslang::EOpSubgroupPartitionedExclusiveMin:
7048 case glslang::EOpSubgroupPartitionedExclusiveMax:
7049 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7050 case glslang::EOpSubgroupPartitionedExclusiveOr:
7051 case glslang::EOpSubgroupPartitionedExclusiveXor:
7052#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007053 return createSubgroupOperation(op, typeId, operands, typeProxy);
7054
Rex Xu9d93a232016-05-05 12:30:44 +08007055#ifdef AMD_EXTENSIONS
7056 case glslang::EOpSwizzleInvocations:
7057 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7058 libCall = spv::SwizzleInvocationsAMD;
7059 break;
7060 case glslang::EOpSwizzleInvocationsMasked:
7061 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7062 libCall = spv::SwizzleInvocationsMaskedAMD;
7063 break;
7064 case glslang::EOpWriteInvocation:
7065 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7066 libCall = spv::WriteInvocationAMD;
7067 break;
7068
7069 case glslang::EOpMin3:
7070 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7071 if (isFloat)
7072 libCall = spv::FMin3AMD;
7073 else {
7074 if (isUnsigned)
7075 libCall = spv::UMin3AMD;
7076 else
7077 libCall = spv::SMin3AMD;
7078 }
7079 break;
7080 case glslang::EOpMax3:
7081 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7082 if (isFloat)
7083 libCall = spv::FMax3AMD;
7084 else {
7085 if (isUnsigned)
7086 libCall = spv::UMax3AMD;
7087 else
7088 libCall = spv::SMax3AMD;
7089 }
7090 break;
7091 case glslang::EOpMid3:
7092 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7093 if (isFloat)
7094 libCall = spv::FMid3AMD;
7095 else {
7096 if (isUnsigned)
7097 libCall = spv::UMid3AMD;
7098 else
7099 libCall = spv::SMid3AMD;
7100 }
7101 break;
7102
7103 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007104 if (typeProxy == glslang::EbtFloat16)
7105 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007106 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7107 libCall = spv::InterpolateAtVertexAMD;
7108 break;
7109#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007110 case glslang::EOpBarrier:
7111 {
7112 // This is for the extended controlBarrier function, with four operands.
7113 // The unextended barrier() goes through createNoArgOperation.
7114 assert(operands.size() == 4);
7115 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7116 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7117 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7118 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7119 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7120 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7121 }
7122 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7123 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7124 }
7125 return 0;
7126 }
7127 break;
7128 case glslang::EOpMemoryBarrier:
7129 {
7130 // This is for the extended memoryBarrier function, with three operands.
7131 // The unextended memoryBarrier() goes through createNoArgOperation.
7132 assert(operands.size() == 3);
7133 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7134 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7135 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7136 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7137 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7138 }
7139 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7140 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7141 }
7142 return 0;
7143 }
7144 break;
Chao Chen3c366992018-09-19 11:41:59 -07007145
7146#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007147 case glslang::EOpReportIntersectionNV:
7148 {
7149 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007150 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007151 }
7152 break;
7153 case glslang::EOpTraceNV:
7154 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007155 builder.createNoResultOp(spv::OpTraceNV, operands);
7156 return 0;
7157 }
7158 break;
7159 case glslang::EOpExecuteCallableNV:
7160 {
7161 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007162 return 0;
7163 }
7164 break;
Chao Chen3c366992018-09-19 11:41:59 -07007165 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7166 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7167 return 0;
7168#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007169 case glslang::EOpCooperativeMatrixMulAdd:
7170 opCode = spv::OpCooperativeMatrixMulAddNV;
7171 break;
7172
John Kessenich140f3df2015-06-26 16:58:36 -06007173 default:
7174 return 0;
7175 }
7176
7177 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007178 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007179 // Use an extended instruction from the standard library.
7180 // Construct the call arguments, without modifying the original operands vector.
7181 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7182 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007183 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007184 } else if (opCode == spv::OpDot && !isFloat) {
7185 // int dot(int, int)
7186 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7187 const int componentCount = builder.getNumComponents(operands[0]);
7188 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7189 builder.setPrecision(mulOp, precision);
7190 id = builder.createCompositeExtract(mulOp, typeId, 0);
7191 for (int i = 1; i < componentCount; ++i) {
7192 builder.setPrecision(id, precision);
7193 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7194 }
John Kessenich2359bd02015-12-06 19:29:11 -07007195 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007196 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007197 case 0:
7198 // should all be handled by visitAggregate and createNoArgOperation
7199 assert(0);
7200 return 0;
7201 case 1:
7202 // should all be handled by createUnaryOperation
7203 assert(0);
7204 return 0;
7205 case 2:
7206 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7207 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007208 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007209 // anything 3 or over doesn't have l-value operands, so all should be consumed
7210 assert(consumedOperands == operands.size());
7211 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007212 break;
7213 }
7214 }
7215
John Kessenich55e7d112015-11-15 21:33:39 -07007216 // Decode the return types that were structures
7217 switch (op) {
7218 case glslang::EOpAddCarry:
7219 case glslang::EOpSubBorrow:
7220 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7221 id = builder.createCompositeExtract(id, typeId0, 0);
7222 break;
7223 case glslang::EOpUMulExtended:
7224 case glslang::EOpIMulExtended:
7225 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7226 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7227 break;
7228 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007229 {
7230 assert(operands.size() == 2);
7231 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7232 // "exp" is floating-point type (from HLSL intrinsic)
7233 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7234 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7235 builder.createStore(member1, operands[1]);
7236 } else
7237 // "exp" is integer type (from GLSL built-in function)
7238 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7239 id = builder.createCompositeExtract(id, typeId0, 0);
7240 }
John Kessenich55e7d112015-11-15 21:33:39 -07007241 break;
7242 default:
7243 break;
7244 }
7245
John Kessenich32cfd492016-02-02 12:37:46 -07007246 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007247}
7248
Rex Xu9d93a232016-05-05 12:30:44 +08007249// Intrinsics with no arguments (or no return value, and no precision).
7250spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007251{
Jeff Bolz36831c92018-09-05 10:11:41 -05007252 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7253 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007254
7255 switch (op) {
7256 case glslang::EOpEmitVertex:
7257 builder.createNoResultOp(spv::OpEmitVertex);
7258 return 0;
7259 case glslang::EOpEndPrimitive:
7260 builder.createNoResultOp(spv::OpEndPrimitive);
7261 return 0;
7262 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007263 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007264 if (glslangIntermediate->usingVulkanMemoryModel()) {
7265 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7266 spv::MemorySemanticsOutputMemoryKHRMask |
7267 spv::MemorySemanticsAcquireReleaseMask);
7268 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7269 } else {
7270 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7271 }
John Kessenich82979362017-12-11 04:02:24 -07007272 } else {
7273 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7274 spv::MemorySemanticsWorkgroupMemoryMask |
7275 spv::MemorySemanticsAcquireReleaseMask);
7276 }
John Kessenich140f3df2015-06-26 16:58:36 -06007277 return 0;
7278 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007279 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7280 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007281 return 0;
7282 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007283 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7284 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007285 return 0;
7286 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007287 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7288 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007289 return 0;
7290 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007291 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7292 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007293 return 0;
7294 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007295 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7296 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007297 return 0;
7298 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007299 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7300 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007301 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007302 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007303 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007304 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007305 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007306 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007307 case glslang::EOpDeviceMemoryBarrier:
7308 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7309 spv::MemorySemanticsImageMemoryMask |
7310 spv::MemorySemanticsAcquireReleaseMask);
7311 return 0;
7312 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7313 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7314 spv::MemorySemanticsImageMemoryMask |
7315 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007316 return 0;
7317 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007318 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7319 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007320 return 0;
7321 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007322 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7323 spv::MemorySemanticsWorkgroupMemoryMask |
7324 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007325 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007326 case glslang::EOpSubgroupBarrier:
7327 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7328 spv::MemorySemanticsAcquireReleaseMask);
7329 return spv::NoResult;
7330 case glslang::EOpSubgroupMemoryBarrier:
7331 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7332 spv::MemorySemanticsAcquireReleaseMask);
7333 return spv::NoResult;
7334 case glslang::EOpSubgroupMemoryBarrierBuffer:
7335 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7336 spv::MemorySemanticsAcquireReleaseMask);
7337 return spv::NoResult;
7338 case glslang::EOpSubgroupMemoryBarrierImage:
7339 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7340 spv::MemorySemanticsAcquireReleaseMask);
7341 return spv::NoResult;
7342 case glslang::EOpSubgroupMemoryBarrierShared:
7343 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7344 spv::MemorySemanticsAcquireReleaseMask);
7345 return spv::NoResult;
7346 case glslang::EOpSubgroupElect: {
7347 std::vector<spv::Id> operands;
7348 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7349 }
Rex Xu9d93a232016-05-05 12:30:44 +08007350#ifdef AMD_EXTENSIONS
7351 case glslang::EOpTime:
7352 {
7353 std::vector<spv::Id> args; // Dummy arguments
7354 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7355 return builder.setPrecision(id, precision);
7356 }
7357#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007358#ifdef NV_EXTENSIONS
7359 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007360 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007361 return 0;
7362 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007363 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007364 return 0;
7365#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007366 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007367 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007368 return 0;
7369 }
7370}
7371
7372spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7373{
John Kessenich2f273362015-07-18 22:34:27 -06007374 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007375 spv::Id id;
7376 if (symbolValues.end() != iter) {
7377 id = iter->second;
7378 return id;
7379 }
7380
7381 // it was not found, create it
7382 id = createSpvVariable(symbol);
7383 symbolValues[symbol->getId()] = id;
7384
Rex Xuc884b4a2016-06-29 15:03:44 +08007385 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007386 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7387 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7388 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007389#ifdef NV_EXTENSIONS
7390 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7391#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007392 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007393 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007394 if (symbol->getQualifier().hasIndex())
7395 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7396 if (symbol->getQualifier().hasComponent())
7397 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007398 // atomic counters use this:
7399 if (symbol->getQualifier().hasOffset())
7400 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007401 }
7402
scygan2c864272016-05-18 18:09:17 +02007403 if (symbol->getQualifier().hasLocation())
7404 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007405 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007406 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007407 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007408 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007409 }
John Kessenich140f3df2015-06-26 16:58:36 -06007410 if (symbol->getQualifier().hasSet())
7411 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007412 else if (IsDescriptorResource(symbol->getType())) {
7413 // default to 0
7414 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7415 }
John Kessenich140f3df2015-06-26 16:58:36 -06007416 if (symbol->getQualifier().hasBinding())
7417 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007418 else if (IsDescriptorResource(symbol->getType())) {
7419 // default to 0
7420 builder.addDecoration(id, spv::DecorationBinding, 0);
7421 }
John Kessenich6c292d32016-02-15 20:58:50 -07007422 if (symbol->getQualifier().hasAttachment())
7423 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007424 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007425 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007426 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007427 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007428 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7429 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7430 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7431 }
7432 if (symbol->getQualifier().hasXfbOffset())
7433 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007434 }
7435
Rex Xu1da878f2016-02-21 20:59:01 +08007436 if (symbol->getType().isImage()) {
7437 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007438 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007439 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007440 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007441 }
7442
John Kessenich140f3df2015-06-26 16:58:36 -06007443 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007444 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007445 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007446 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007447
John Kessenich5611c6d2018-04-05 11:25:02 -06007448 // nonuniform
7449 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7450
John Kessenichecba76f2017-01-06 00:34:48 -07007451#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007452 if (builtIn == spv::BuiltInSampleMask) {
7453 spv::Decoration decoration;
7454 // GL_NV_sample_mask_override_coverage extension
7455 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007456 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007457 else
7458 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007459 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007460 if (decoration != spv::DecorationMax) {
7461 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7462 }
7463 }
chaoc771d89f2017-01-13 01:10:53 -08007464 else if (builtIn == spv::BuiltInLayer) {
7465 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007466 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007467 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007468 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7469 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7470 }
John Kessenichb41bff62017-08-11 13:07:17 -06007471 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007472 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7473 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007474 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7475 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7476 }
7477 }
7478
chaoc6e5acae2016-12-20 13:28:52 -08007479 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007480 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007481 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007482 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7483 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007484 if (symbol->getQualifier().pervertexNV) {
7485 builder.addDecoration(id, spv::DecorationPerVertexNV);
7486 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7487 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7488 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007489#endif
7490
John Kessenich5d610ee2018-03-07 18:05:55 -07007491 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7492 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7493 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7494 symbol->getType().getQualifier().semanticName);
7495 }
7496
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007497 if (symbol->getBasicType() == glslang::EbtReference) {
7498 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7499 }
7500
John Kessenich140f3df2015-06-26 16:58:36 -06007501 return id;
7502}
7503
Chao Chen3c366992018-09-19 11:41:59 -07007504#ifdef NV_EXTENSIONS
7505// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7506void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7507{
7508 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007509 if (qualifier.perPrimitiveNV) {
7510 // Need to add capability/extension for fragment shader.
7511 // Mesh shader already adds this by default.
7512 if (glslangIntermediate->getStage() == EShLangFragment) {
7513 builder.addCapability(spv::CapabilityMeshShadingNV);
7514 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7515 }
Chao Chen3c366992018-09-19 11:41:59 -07007516 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007517 }
Chao Chen3c366992018-09-19 11:41:59 -07007518 if (qualifier.perViewNV)
7519 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7520 if (qualifier.perTaskNV)
7521 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7522 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007523 if (qualifier.perPrimitiveNV) {
7524 // Need to add capability/extension for fragment shader.
7525 // Mesh shader already adds this by default.
7526 if (glslangIntermediate->getStage() == EShLangFragment) {
7527 builder.addCapability(spv::CapabilityMeshShadingNV);
7528 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7529 }
Chao Chen3c366992018-09-19 11:41:59 -07007530 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007531 }
Chao Chen3c366992018-09-19 11:41:59 -07007532 if (qualifier.perViewNV)
7533 builder.addDecoration(id, spv::DecorationPerViewNV);
7534 if (qualifier.perTaskNV)
7535 builder.addDecoration(id, spv::DecorationPerTaskNV);
7536 }
7537}
7538#endif
7539
John Kessenich55e7d112015-11-15 21:33:39 -07007540// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007541// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007542//
7543// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7544//
7545// Recursively walk the nodes. The nodes form a tree whose leaves are
7546// regular constants, which themselves are trees that createSpvConstant()
7547// recursively walks. So, this function walks the "top" of the tree:
7548// - emit specialization constant-building instructions for specConstant
7549// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007550spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007551{
John Kessenich7cc0e282016-03-20 00:46:02 -06007552 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007553
qining4f4bb812016-04-03 23:55:17 -04007554 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007555 if (! node.getQualifier().specConstant) {
7556 // hand off to the non-spec-constant path
7557 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7558 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007559 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007560 nextConst, false);
7561 }
7562
7563 // We now know we have a specialization constant to build
7564
John Kessenichd94c0032016-05-30 19:29:40 -06007565 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007566 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7567 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7568 std::vector<spv::Id> dimConstId;
7569 for (int dim = 0; dim < 3; ++dim) {
7570 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7571 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007572 if (specConst) {
7573 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7574 glslangIntermediate->getLocalSizeSpecId(dim));
7575 }
qining4f4bb812016-04-03 23:55:17 -04007576 }
7577 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7578 }
7579
7580 // An AST node labelled as specialization constant should be a symbol node.
7581 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7582 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007583 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007584 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007585 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7586 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7587 // will set the builder into spec constant op instruction generating mode.
7588 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007589 result = accessChainLoad(sub_tree->getType());
7590 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007591 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007592 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007593 } else {
7594 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007595 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007596 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007597 builder.addName(result, sn->getName().c_str());
7598 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007599 }
qining4f4bb812016-04-03 23:55:17 -04007600
7601 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7602 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007603 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007604 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007605}
7606
John Kessenich140f3df2015-06-26 16:58:36 -06007607// Use 'consts' as the flattened glslang source of scalar constants to recursively
7608// build the aggregate SPIR-V constant.
7609//
7610// If there are not enough elements present in 'consts', 0 will be substituted;
7611// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7612//
qining08408382016-03-21 09:51:37 -04007613spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007614{
7615 // vector of constants for SPIR-V
7616 std::vector<spv::Id> spvConsts;
7617
7618 // Type is used for struct and array constants
7619 spv::Id typeId = convertGlslangToSpvType(glslangType);
7620
7621 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007622 glslang::TType elementType(glslangType, 0);
7623 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007624 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007625 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007626 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007627 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007628 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007629 } else if (glslangType.isCoopMat()) {
7630 glslang::TType componentType(glslangType.getBasicType());
7631 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007632 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007633 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7634 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007635 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007636 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007637 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7638 bool zero = nextConst >= consts.size();
7639 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007640 case glslang::EbtInt8:
7641 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7642 break;
7643 case glslang::EbtUint8:
7644 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7645 break;
7646 case glslang::EbtInt16:
7647 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7648 break;
7649 case glslang::EbtUint16:
7650 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7651 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007652 case glslang::EbtInt:
7653 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7654 break;
7655 case glslang::EbtUint:
7656 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7657 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007658 case glslang::EbtInt64:
7659 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7660 break;
7661 case glslang::EbtUint64:
7662 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7663 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007664 case glslang::EbtFloat:
7665 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7666 break;
7667 case glslang::EbtDouble:
7668 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7669 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007670 case glslang::EbtFloat16:
7671 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7672 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007673 case glslang::EbtBool:
7674 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7675 break;
7676 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007677 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007678 break;
7679 }
7680 ++nextConst;
7681 }
7682 } else {
7683 // we have a non-aggregate (scalar) constant
7684 bool zero = nextConst >= consts.size();
7685 spv::Id scalar = 0;
7686 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007687 case glslang::EbtInt8:
7688 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7689 break;
7690 case glslang::EbtUint8:
7691 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7692 break;
7693 case glslang::EbtInt16:
7694 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7695 break;
7696 case glslang::EbtUint16:
7697 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7698 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007699 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007700 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007701 break;
7702 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007703 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007704 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007705 case glslang::EbtInt64:
7706 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7707 break;
7708 case glslang::EbtUint64:
7709 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7710 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007711 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007712 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007713 break;
7714 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007715 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007716 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007717 case glslang::EbtFloat16:
7718 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7719 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007720 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007721 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007722 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007723 case glslang::EbtReference:
7724 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7725 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7726 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007727 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007728 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007729 break;
7730 }
7731 ++nextConst;
7732 return scalar;
7733 }
7734
7735 return builder.makeCompositeConstant(typeId, spvConsts);
7736}
7737
John Kessenich7c1aa102015-10-15 13:29:11 -06007738// Return true if the node is a constant or symbol whose reading has no
7739// non-trivial observable cost or effect.
7740bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7741{
7742 // don't know what this is
7743 if (node == nullptr)
7744 return false;
7745
7746 // a constant is safe
7747 if (node->getAsConstantUnion() != nullptr)
7748 return true;
7749
7750 // not a symbol means non-trivial
7751 if (node->getAsSymbolNode() == nullptr)
7752 return false;
7753
7754 // a symbol, depends on what's being read
7755 switch (node->getType().getQualifier().storage) {
7756 case glslang::EvqTemporary:
7757 case glslang::EvqGlobal:
7758 case glslang::EvqIn:
7759 case glslang::EvqInOut:
7760 case glslang::EvqConst:
7761 case glslang::EvqConstReadOnly:
7762 case glslang::EvqUniform:
7763 return true;
7764 default:
7765 return false;
7766 }
qining25262b32016-05-06 17:25:16 -04007767}
John Kessenich7c1aa102015-10-15 13:29:11 -06007768
7769// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007770// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007771// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007772// Return true if trivial.
7773bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7774{
7775 if (node == nullptr)
7776 return false;
7777
John Kessenich84cc15f2017-05-24 16:44:47 -06007778 // count non scalars as trivial, as well as anything coming from HLSL
7779 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007780 return true;
7781
John Kessenich7c1aa102015-10-15 13:29:11 -06007782 // symbols and constants are trivial
7783 if (isTrivialLeaf(node))
7784 return true;
7785
7786 // otherwise, it needs to be a simple operation or one or two leaf nodes
7787
7788 // not a simple operation
7789 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7790 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7791 if (binaryNode == nullptr && unaryNode == nullptr)
7792 return false;
7793
7794 // not on leaf nodes
7795 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7796 return false;
7797
7798 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7799 return false;
7800 }
7801
7802 switch (node->getAsOperator()->getOp()) {
7803 case glslang::EOpLogicalNot:
7804 case glslang::EOpConvIntToBool:
7805 case glslang::EOpConvUintToBool:
7806 case glslang::EOpConvFloatToBool:
7807 case glslang::EOpConvDoubleToBool:
7808 case glslang::EOpEqual:
7809 case glslang::EOpNotEqual:
7810 case glslang::EOpLessThan:
7811 case glslang::EOpGreaterThan:
7812 case glslang::EOpLessThanEqual:
7813 case glslang::EOpGreaterThanEqual:
7814 case glslang::EOpIndexDirect:
7815 case glslang::EOpIndexDirectStruct:
7816 case glslang::EOpLogicalXor:
7817 case glslang::EOpAny:
7818 case glslang::EOpAll:
7819 return true;
7820 default:
7821 return false;
7822 }
7823}
7824
7825// Emit short-circuiting code, where 'right' is never evaluated unless
7826// the left side is true (for &&) or false (for ||).
7827spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7828{
7829 spv::Id boolTypeId = builder.makeBoolType();
7830
7831 // emit left operand
7832 builder.clearAccessChain();
7833 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007834 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007835
7836 // Operands to accumulate OpPhi operands
7837 std::vector<spv::Id> phiOperands;
7838 // accumulate left operand's phi information
7839 phiOperands.push_back(leftId);
7840 phiOperands.push_back(builder.getBuildPoint()->getId());
7841
7842 // Make the two kinds of operation symmetric with a "!"
7843 // || => emit "if (! left) result = right"
7844 // && => emit "if ( left) result = right"
7845 //
7846 // TODO: this runtime "not" for || could be avoided by adding functionality
7847 // to 'builder' to have an "else" without an "then"
7848 if (op == glslang::EOpLogicalOr)
7849 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7850
7851 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007852 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007853
7854 // emit right operand as the "then" part of the "if"
7855 builder.clearAccessChain();
7856 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007857 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007858
7859 // accumulate left operand's phi information
7860 phiOperands.push_back(rightId);
7861 phiOperands.push_back(builder.getBuildPoint()->getId());
7862
7863 // finish the "if"
7864 ifBuilder.makeEndIf();
7865
7866 // phi together the two results
7867 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7868}
7869
Frank Henigman541f7bb2018-01-16 00:18:26 -05007870#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007871// Return type Id of the imported set of extended instructions corresponds to the name.
7872// Import this set if it has not been imported yet.
7873spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7874{
7875 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7876 return extBuiltinMap[name];
7877 else {
Rex Xu51596642016-09-21 18:56:12 +08007878 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007879 spv::Id extBuiltins = builder.import(name);
7880 extBuiltinMap[name] = extBuiltins;
7881 return extBuiltins;
7882 }
7883}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007884#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007885
John Kessenich140f3df2015-06-26 16:58:36 -06007886}; // end anonymous namespace
7887
7888namespace glslang {
7889
John Kessenich68d78fd2015-07-12 19:28:10 -06007890void GetSpirvVersion(std::string& version)
7891{
John Kessenich9e55f632015-07-15 10:03:39 -06007892 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007893 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007894 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007895 version = buf;
7896}
7897
John Kessenicha372a3e2017-11-02 22:32:14 -06007898// For low-order part of the generator's magic number. Bump up
7899// when there is a change in the style (e.g., if SSA form changes,
7900// or a different instruction sequence to do something gets used).
7901int GetSpirvGeneratorVersion()
7902{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007903 // return 1; // start
7904 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007905 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007906 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007907 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007908 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7909 // versions 4 and 6 each generate OpArrayLength as it has long been done
7910 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007911}
7912
John Kessenich140f3df2015-06-26 16:58:36 -06007913// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007914void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007915{
7916 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007917 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007918 if (out.fail())
7919 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007920 for (int i = 0; i < (int)spirv.size(); ++i) {
7921 unsigned int word = spirv[i];
7922 out.write((const char*)&word, 4);
7923 }
7924 out.close();
7925}
7926
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007927// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007928void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007929{
7930 std::ofstream out;
7931 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007932 if (out.fail())
7933 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007934 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007935 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007936 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007937 if (varName != nullptr) {
7938 out << "\t #pragma once" << std::endl;
7939 out << "const uint32_t " << varName << "[] = {" << std::endl;
7940 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007941 const int WORDS_PER_LINE = 8;
7942 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7943 out << "\t";
7944 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7945 const unsigned int word = spirv[i + j];
7946 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7947 if (i + j + 1 < (int)spirv.size()) {
7948 out << ",";
7949 }
7950 }
7951 out << std::endl;
7952 }
Flavio15017db2017-02-15 14:29:33 -08007953 if (varName != nullptr) {
7954 out << "};";
7955 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007956 out.close();
7957}
7958
John Kessenich140f3df2015-06-26 16:58:36 -06007959//
7960// Set up the glslang traversal
7961//
John Kessenich4e11b612018-08-30 16:56:59 -06007962void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007963{
Lei Zhang17535f72016-05-04 15:55:59 -04007964 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007965 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007966}
7967
John Kessenich4e11b612018-08-30 16:56:59 -06007968void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007969 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007970{
John Kessenich140f3df2015-06-26 16:58:36 -06007971 TIntermNode* root = intermediate.getTreeRoot();
7972
7973 if (root == 0)
7974 return;
7975
John Kessenich4e11b612018-08-30 16:56:59 -06007976 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007977 if (options == nullptr)
7978 options = &defaultOptions;
7979
John Kessenich4e11b612018-08-30 16:56:59 -06007980 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007981
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007982 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007983 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007984 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007985 it.dumpSpv(spirv);
7986
GregFfb03a552018-03-29 11:49:14 -06007987#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007988 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7989 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007990 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007991 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007992
John Kessenich4e11b612018-08-30 16:56:59 -06007993 if (options->validate)
7994 SpirvToolsValidate(intermediate, spirv, logger);
7995
John Kessenich717c80a2018-08-23 15:17:10 -06007996 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007997 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007998
GregFcd1f1692017-09-21 18:40:22 -06007999#endif
8000
John Kessenich4e11b612018-08-30 16:56:59 -06008001 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008002}
8003
8004}; // end namespace glslang