blob: c513cd18fd83175fbcd943deea373c3ff66a9f71 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
Daniel Koch593a4e02019-05-27 16:46:31 -0400891 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400920
921 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700922 case glslang::EbvBaryCoordNV:
923 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
924 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
925 return spv::BuiltInBaryCoordNV;
926 case glslang::EbvBaryCoordNoPerspNV:
927 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
928 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
929 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400930
931 // mesh shaders
932 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800949 default:
950 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
952}
953
Rex Xufc618912015-09-09 16:42:49 +0800954// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700955spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800956{
957 assert(type.getBasicType() == glslang::EbtSampler);
958
John Kessenich5d0fa972016-02-15 11:57:00 -0700959 // Check for capabilities
960 switch (type.getQualifier().layoutFormat) {
961 case glslang::ElfRg32f:
962 case glslang::ElfRg16f:
963 case glslang::ElfR11fG11fB10f:
964 case glslang::ElfR16f:
965 case glslang::ElfRgba16:
966 case glslang::ElfRgb10A2:
967 case glslang::ElfRg16:
968 case glslang::ElfRg8:
969 case glslang::ElfR16:
970 case glslang::ElfR8:
971 case glslang::ElfRgba16Snorm:
972 case glslang::ElfRg16Snorm:
973 case glslang::ElfRg8Snorm:
974 case glslang::ElfR16Snorm:
975 case glslang::ElfR8Snorm:
976
977 case glslang::ElfRg32i:
978 case glslang::ElfRg16i:
979 case glslang::ElfRg8i:
980 case glslang::ElfR16i:
981 case glslang::ElfR8i:
982
983 case glslang::ElfRgb10a2ui:
984 case glslang::ElfRg32ui:
985 case glslang::ElfRg16ui:
986 case glslang::ElfRg8ui:
987 case glslang::ElfR16ui:
988 case glslang::ElfR8ui:
989 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
990 break;
991
992 default:
993 break;
994 }
995
996 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800997 switch (type.getQualifier().layoutFormat) {
998 case glslang::ElfNone: return spv::ImageFormatUnknown;
999 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1000 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1001 case glslang::ElfR32f: return spv::ImageFormatR32f;
1002 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1003 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1004 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1005 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1006 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1007 case glslang::ElfR16f: return spv::ImageFormatR16f;
1008 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1009 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1010 case glslang::ElfRg16: return spv::ImageFormatRg16;
1011 case glslang::ElfRg8: return spv::ImageFormatRg8;
1012 case glslang::ElfR16: return spv::ImageFormatR16;
1013 case glslang::ElfR8: return spv::ImageFormatR8;
1014 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1015 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1016 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1017 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1018 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1019 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1020 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1021 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1022 case glslang::ElfR32i: return spv::ImageFormatR32i;
1023 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1024 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1025 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1026 case glslang::ElfR16i: return spv::ImageFormatR16i;
1027 case glslang::ElfR8i: return spv::ImageFormatR8i;
1028 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1029 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1030 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1031 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1032 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1033 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1034 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1035 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1036 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1037 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001038 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001039 }
1040}
1041
John Kesseniche18fd202018-01-30 11:01:39 -07001042spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001043{
John Kesseniche18fd202018-01-30 11:01:39 -07001044 if (selectionNode.getFlatten())
1045 return spv::SelectionControlFlattenMask;
1046 if (selectionNode.getDontFlatten())
1047 return spv::SelectionControlDontFlattenMask;
1048 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001049}
1050
John Kesseniche18fd202018-01-30 11:01:39 -07001051spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001052{
John Kesseniche18fd202018-01-30 11:01:39 -07001053 if (switchNode.getFlatten())
1054 return spv::SelectionControlFlattenMask;
1055 if (switchNode.getDontFlatten())
1056 return spv::SelectionControlDontFlattenMask;
1057 return spv::SelectionControlMaskNone;
1058}
1059
John Kessenicha2858d92018-01-31 08:11:18 -07001060// return a non-0 dependency if the dependency argument must be set
1061spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001062 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001063{
1064 spv::LoopControlMask control = spv::LoopControlMaskNone;
1065
1066 if (loopNode.getDontUnroll())
1067 control = control | spv::LoopControlDontUnrollMask;
1068 if (loopNode.getUnroll())
1069 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001070 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001071 control = control | spv::LoopControlDependencyInfiniteMask;
1072 else if (loopNode.getLoopDependency() > 0) {
1073 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001074 operands.push_back((unsigned int)loopNode.getLoopDependency());
1075 }
1076 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1077 if (loopNode.getMinIterations() > 0) {
1078 control = control | spv::LoopControlMinIterationsMask;
1079 operands.push_back(loopNode.getMinIterations());
1080 }
1081 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1082 control = control | spv::LoopControlMaxIterationsMask;
1083 operands.push_back(loopNode.getMaxIterations());
1084 }
1085 if (loopNode.getIterationMultiple() > 1) {
1086 control = control | spv::LoopControlIterationMultipleMask;
1087 operands.push_back(loopNode.getIterationMultiple());
1088 }
1089 if (loopNode.getPeelCount() > 0) {
1090 control = control | spv::LoopControlPeelCountMask;
1091 operands.push_back(loopNode.getPeelCount());
1092 }
1093 if (loopNode.getPartialCount() > 0) {
1094 control = control | spv::LoopControlPartialCountMask;
1095 operands.push_back(loopNode.getPartialCount());
1096 }
John Kessenicha2858d92018-01-31 08:11:18 -07001097 }
John Kesseniche18fd202018-01-30 11:01:39 -07001098
1099 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001100}
1101
John Kessenicha5c5fb62017-05-05 05:09:58 -06001102// Translate glslang type to SPIR-V storage class.
1103spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1104{
1105 if (type.getQualifier().isPipeInput())
1106 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001107 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001108 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109
1110 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1111 type.getQualifier().storage == glslang::EvqUniform) {
1112 if (type.getBasicType() == glslang::EbtAtomicUint)
1113 return spv::StorageClassAtomicCounter;
1114 if (type.containsOpaque())
1115 return spv::StorageClassUniformConstant;
1116 }
1117
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001118#ifdef NV_EXTENSIONS
1119 if (type.getQualifier().isUniformOrBuffer() &&
1120 type.getQualifier().layoutShaderRecordNV) {
1121 return spv::StorageClassShaderRecordBufferNV;
1122 }
1123#endif
1124
John Kessenichbed4e4f2017-09-08 02:38:07 -06001125 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001126 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001128 }
1129
1130 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001131 if (type.getQualifier().layoutPushConstant)
1132 return spv::StorageClassPushConstant;
1133 if (type.getBasicType() == glslang::EbtBlock)
1134 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001135 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001136 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001137
1138 switch (type.getQualifier().storage) {
1139 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1140 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1141 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1142 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001143#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001144 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1145 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1146 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1147 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1148 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001149#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001150 default:
1151 assert(0);
1152 break;
1153 }
1154
1155 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001156}
1157
John Kessenich5611c6d2018-04-05 11:25:02 -06001158// Add capabilities pertaining to how an array is indexed.
1159void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1160 const glslang::TType& indexType)
1161{
1162 if (indexType.getQualifier().isNonUniform()) {
1163 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001164 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001165 if (baseType.getBasicType() == glslang::EbtSampler) {
1166 if (baseType.getQualifier().hasAttachment())
1167 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1169 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1171 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1172 else if (baseType.isImage())
1173 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1174 else if (baseType.isTexture())
1175 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1176 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1177 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1178 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1179 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1180 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1181 }
1182 } else {
1183 // assume a dynamically uniform index
1184 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001185 if (baseType.getQualifier().hasAttachment()) {
1186 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001187 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001188 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1189 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001190 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001191 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1192 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001193 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001194 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001195 }
1196 }
1197}
1198
qining25262b32016-05-06 17:25:16 -04001199// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001200// descriptor set.
1201bool IsDescriptorResource(const glslang::TType& type)
1202{
John Kessenichf7497e22016-03-08 21:36:22 -07001203 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001204 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001205 return type.getQualifier().isUniformOrBuffer() &&
1206#ifdef NV_EXTENSIONS
1207 ! type.getQualifier().layoutShaderRecordNV &&
1208#endif
1209 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001210
1211 // non block...
1212 // basically samplerXXX/subpass/sampler/texture are all included
1213 // if they are the global-scope-class, not the function parameter
1214 // (or local, if they ever exist) class.
1215 if (type.getBasicType() == glslang::EbtSampler)
1216 return type.getQualifier().isUniformOrBuffer();
1217
1218 // None of the above.
1219 return false;
1220}
1221
John Kesseniche0b6cad2015-12-24 10:30:13 -07001222void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1223{
1224 if (child.layoutMatrix == glslang::ElmNone)
1225 child.layoutMatrix = parent.layoutMatrix;
1226
1227 if (parent.invariant)
1228 child.invariant = true;
1229 if (parent.nopersp)
1230 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001231#ifdef AMD_EXTENSIONS
1232 if (parent.explicitInterp)
1233 child.explicitInterp = true;
1234#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001235 if (parent.flat)
1236 child.flat = true;
1237 if (parent.centroid)
1238 child.centroid = true;
1239 if (parent.patch)
1240 child.patch = true;
1241 if (parent.sample)
1242 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001243 if (parent.coherent)
1244 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001245 if (parent.devicecoherent)
1246 child.devicecoherent = true;
1247 if (parent.queuefamilycoherent)
1248 child.queuefamilycoherent = true;
1249 if (parent.workgroupcoherent)
1250 child.workgroupcoherent = true;
1251 if (parent.subgroupcoherent)
1252 child.subgroupcoherent = true;
1253 if (parent.nonprivate)
1254 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001255 if (parent.volatil)
1256 child.volatil = true;
1257 if (parent.restrict)
1258 child.restrict = true;
1259 if (parent.readonly)
1260 child.readonly = true;
1261 if (parent.writeonly)
1262 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001263#ifdef NV_EXTENSIONS
1264 if (parent.perPrimitiveNV)
1265 child.perPrimitiveNV = true;
1266 if (parent.perViewNV)
1267 child.perViewNV = true;
1268 if (parent.perTaskNV)
1269 child.perTaskNV = true;
1270#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001271}
1272
John Kessenichf2b7f332016-09-01 17:05:23 -06001273bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001274{
John Kessenich7b9fa252016-01-21 18:56:57 -07001275 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001276 // - struct members might inherit from a struct declaration
1277 // (note that non-block structs don't explicitly inherit,
1278 // only implicitly, meaning no decoration involved)
1279 // - affect decorations on the struct members
1280 // (note smooth does not, and expecting something like volatile
1281 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001282 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001283 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001284}
1285
John Kessenich140f3df2015-06-26 16:58:36 -06001286//
1287// Implement the TGlslangToSpvTraverser class.
1288//
1289
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001290TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001291 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1292 : TIntermTraverser(true, false, true),
1293 options(options),
1294 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001295 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001296 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001297 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001298 glslangIntermediate(glslangIntermediate)
1299{
1300 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1301
1302 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001303 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1304 glslangIntermediate->getVersion());
1305
John Kessenich121853f2017-05-31 17:11:16 -06001306 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001307 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001308 builder.setSourceFile(glslangIntermediate->getSourceFile());
1309
1310 // Set the source shader's text. If for SPV version 1.0, include
1311 // a preamble in comments stating the OpModuleProcessed instructions.
1312 // Otherwise, emit those as actual instructions.
1313 std::string text;
1314 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1315 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001316 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001317 text.append("// OpModuleProcessed ");
1318 text.append(processes[p]);
1319 text.append("\n");
1320 } else
1321 builder.addModuleProcessed(processes[p]);
1322 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001323 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001324 text.append("#line 1\n");
1325 text.append(glslangIntermediate->getSourceText());
1326 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001327 // Pass name and text for all included files
1328 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1329 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1330 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001331 }
John Kessenich140f3df2015-06-26 16:58:36 -06001332 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001333
1334 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1335 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1336
1337 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1338 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1339 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1340 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1341 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 memoryModel = spv::MemoryModelVulkanKHR;
1344 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001346 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001347 builder.setMemoryModel(addressingModel, memoryModel);
1348
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001349 if (glslangIntermediate->usingVariablePointers()) {
1350 builder.addCapability(spv::CapabilityVariablePointers);
1351 }
1352
John Kessenicheee9d532016-09-19 18:09:30 -06001353 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1354 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001357 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1358 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001359 builder.addSourceExtension(it->c_str());
1360
1361 // Add the top-level modes for this shader.
1362
John Kessenich92187592016-02-01 13:45:25 -07001363 if (glslangIntermediate->getXfbMode()) {
1364 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001365 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001366 }
John Kessenich140f3df2015-06-26 16:58:36 -06001367
1368 unsigned int mode;
1369 switch (glslangIntermediate->getStage()) {
1370 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001371 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001372 break;
1373
steve-lunarge7412492017-03-23 11:56:07 -06001374 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001375 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001376 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001377
steve-lunarge7412492017-03-23 11:56:07 -06001378 glslang::TLayoutGeometry primitive;
1379
1380 if (glslangIntermediate->getStage() == EShLangTessControl) {
1381 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1382 primitive = glslangIntermediate->getOutputPrimitive();
1383 } else {
1384 primitive = glslangIntermediate->getInputPrimitive();
1385 }
1386
1387 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001388 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1389 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1390 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001391 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001392 }
John Kessenich4016e382016-07-15 11:53:56 -06001393 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001394 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1395
John Kesseniche6903322015-10-13 16:29:02 -06001396 switch (glslangIntermediate->getVertexSpacing()) {
1397 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1398 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1399 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001400 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001401 }
John Kessenich4016e382016-07-15 11:53:56 -06001402 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001403 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1404
1405 switch (glslangIntermediate->getVertexOrder()) {
1406 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1407 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001408 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001409 }
John Kessenich4016e382016-07-15 11:53:56 -06001410 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001411 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1412
1413 if (glslangIntermediate->getPointMode())
1414 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 break;
1416
1417 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001418 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 switch (glslangIntermediate->getInputPrimitive()) {
1420 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1421 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1422 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001423 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001424 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001425 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001426 }
John Kessenich4016e382016-07-15 11:53:56 -06001427 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1431
1432 switch (glslangIntermediate->getOutputPrimitive()) {
1433 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1434 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1435 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001436 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001437 }
John Kessenich4016e382016-07-15 11:53:56 -06001438 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001439 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1441 break;
1442
1443 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001444 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001445 if (glslangIntermediate->getPixelCenterInteger())
1446 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001447
John Kessenich140f3df2015-06-26 16:58:36 -06001448 if (glslangIntermediate->getOriginUpperLeft())
1449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001450 else
1451 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001452
1453 if (glslangIntermediate->getEarlyFragmentTests())
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1455
chaocc1204522017-06-30 17:14:30 -07001456 if (glslangIntermediate->getPostDepthCoverage()) {
1457 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1459 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1460 }
1461
John Kesseniche6903322015-10-13 16:29:02 -06001462 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001463 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1464 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001465 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001466 }
John Kessenich4016e382016-07-15 11:53:56 -06001467 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001468 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1469
1470 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1471 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001472 break;
1473
1474 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001475 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001476 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1477 glslangIntermediate->getLocalSize(1),
1478 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001479#ifdef NV_EXTENSIONS
1480 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1481 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1483 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1484 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1485 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1487 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1488 }
1489#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001490 break;
1491
Chao Chen3c366992018-09-19 11:41:59 -07001492#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001493 case EShLangRayGenNV:
1494 case EShLangIntersectNV:
1495 case EShLangAnyHitNV:
1496 case EShLangClosestHitNV:
1497 case EShLangMissNV:
1498 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001499 builder.addCapability(spv::CapabilityRayTracingNV);
1500 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001501 break;
Chao Chen3c366992018-09-19 11:41:59 -07001502 case EShLangTaskNV:
1503 case EShLangMeshNV:
1504 builder.addCapability(spv::CapabilityMeshShadingNV);
1505 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1507 glslangIntermediate->getLocalSize(1),
1508 glslangIntermediate->getLocalSize(2));
1509 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1510 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1511 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1512
1513 switch (glslangIntermediate->getOutputPrimitive()) {
1514 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1515 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1516 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1517 default: mode = spv::ExecutionModeMax; break;
1518 }
1519 if (mode != spv::ExecutionModeMax)
1520 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1521 }
1522 break;
1523#endif
1524
John Kessenich140f3df2015-06-26 16:58:36 -06001525 default:
1526 break;
1527 }
John Kessenich140f3df2015-06-26 16:58:36 -06001528}
1529
John Kessenichfca82622016-11-26 13:23:20 -07001530// Finish creating SPV, after the traversal is complete.
1531void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001532{
John Kessenichf04c51b2018-08-03 15:56:12 -06001533 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001534 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001535 builder.setBuildPoint(shaderEntry->getLastBlock());
1536 builder.leaveFunction();
1537 }
1538
John Kessenich7ba63412015-12-20 17:37:07 -07001539 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001540 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1541 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001542
John Kessenichf04c51b2018-08-03 15:56:12 -06001543 // Add capabilities, extensions, remove unneeded decorations, etc.,
1544 // based on the resulting SPIR-V.
1545 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001546}
1547
John Kessenichfca82622016-11-26 13:23:20 -07001548// Write the SPV into 'out'.
1549void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001550{
John Kessenichfca82622016-11-26 13:23:20 -07001551 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001552}
1553
1554//
1555// Implement the traversal functions.
1556//
1557// Return true from interior nodes to have the external traversal
1558// continue on to children. Return false if children were
1559// already processed.
1560//
1561
1562//
qining25262b32016-05-06 17:25:16 -04001563// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001564// - uniform/input reads
1565// - output writes
1566// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1567// - something simple that degenerates into the last bullet
1568//
1569void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1570{
qining75d1d802016-04-06 14:42:01 -04001571 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1572 if (symbol->getType().getQualifier().isSpecConstant())
1573 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1574
John Kessenich140f3df2015-06-26 16:58:36 -06001575 // getSymbolId() will set up all the IO decorations on the first call.
1576 // Formal function parameters were mapped during makeFunctions().
1577 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001578
1579 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1580 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001581 // Consider adding to the OpEntryPoint interface list.
1582 // Only looking at structures if they have at least one member.
1583 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1584 spv::StorageClass sc = builder.getStorageClass(id);
1585 // Before SPIR-V 1.4, we only want to include Input and Output.
1586 // Starting with SPIR-V 1.4, we want all globals.
1587 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1588 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001589 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001590 }
John Kessenich5f77d862017-09-19 11:09:59 -06001591 }
John Kessenich7ba63412015-12-20 17:37:07 -07001592 }
1593
1594 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001595 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001596 // Prepare to generate code for the access
1597
1598 // L-value chains will be computed left to right. We're on the symbol now,
1599 // which is the left-most part of the access chain, so now is "clear" time,
1600 // followed by setting the base.
1601 builder.clearAccessChain();
1602
1603 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001604 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001605 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001606 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001607 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001608 // These are also pure R-values.
1609 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001610 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001611 builder.setAccessChainRValue(id);
1612 else
1613 builder.setAccessChainLValue(id);
1614 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001615
1616 // Process linkage-only nodes for any special additional interface work.
1617 if (linkageOnly) {
1618 if (glslangIntermediate->getHlslFunctionality1()) {
1619 // Map implicit counter buffers to their originating buffers, which should have been
1620 // seen by now, given earlier pruning of unused counters, and preservation of order
1621 // of declaration.
1622 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1623 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1624 // Save possible originating buffers for counter buffers, keyed by
1625 // making the potential counter-buffer name.
1626 std::string keyName = symbol->getName().c_str();
1627 keyName = glslangIntermediate->addCounterBufferName(keyName);
1628 counterOriginator[keyName] = symbol;
1629 } else {
1630 // Handle a counter buffer, by finding the saved originating buffer.
1631 std::string keyName = symbol->getName().c_str();
1632 auto it = counterOriginator.find(keyName);
1633 if (it != counterOriginator.end()) {
1634 id = getSymbolId(it->second);
1635 if (id != spv::NoResult) {
1636 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001637 if (counterId != spv::NoResult) {
1638 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001639 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001640 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001641 }
1642 }
1643 }
1644 }
1645 }
1646 }
John Kessenich140f3df2015-06-26 16:58:36 -06001647}
1648
1649bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1650{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001651 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001652
qining40887662016-04-03 22:20:42 -04001653 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1654 if (node->getType().getQualifier().isSpecConstant())
1655 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1656
John Kessenich140f3df2015-06-26 16:58:36 -06001657 // First, handle special cases
1658 switch (node->getOp()) {
1659 case glslang::EOpAssign:
1660 case glslang::EOpAddAssign:
1661 case glslang::EOpSubAssign:
1662 case glslang::EOpMulAssign:
1663 case glslang::EOpVectorTimesMatrixAssign:
1664 case glslang::EOpVectorTimesScalarAssign:
1665 case glslang::EOpMatrixTimesScalarAssign:
1666 case glslang::EOpMatrixTimesMatrixAssign:
1667 case glslang::EOpDivAssign:
1668 case glslang::EOpModAssign:
1669 case glslang::EOpAndAssign:
1670 case glslang::EOpInclusiveOrAssign:
1671 case glslang::EOpExclusiveOrAssign:
1672 case glslang::EOpLeftShiftAssign:
1673 case glslang::EOpRightShiftAssign:
1674 // A bin-op assign "a += b" means the same thing as "a = a + b"
1675 // where a is evaluated before b. For a simple assignment, GLSL
1676 // says to evaluate the left before the right. So, always, left
1677 // node then right node.
1678 {
1679 // get the left l-value, save it away
1680 builder.clearAccessChain();
1681 node->getLeft()->traverse(this);
1682 spv::Builder::AccessChain lValue = builder.getAccessChain();
1683
1684 // evaluate the right
1685 builder.clearAccessChain();
1686 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001687 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001688
1689 if (node->getOp() != glslang::EOpAssign) {
1690 // the left is also an r-value
1691 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001692 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001693
1694 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001695 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001696 TranslateNoContractionDecoration(node->getType().getQualifier()),
1697 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001698 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001699 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1700 node->getType().getBasicType());
1701
1702 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001703 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001704 }
1705
1706 // store the result
1707 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001708 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001709
1710 // assignments are expressions having an rValue after they are evaluated...
1711 builder.clearAccessChain();
1712 builder.setAccessChainRValue(rValue);
1713 }
1714 return false;
1715 case glslang::EOpIndexDirect:
1716 case glslang::EOpIndexDirectStruct:
1717 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001718 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001719 // Get the left part of the access chain.
1720 node->getLeft()->traverse(this);
1721
1722 // Add the next element in the chain
1723
David Netoa901ffe2016-06-08 14:11:40 +01001724 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001725 if (! node->getLeft()->getType().isArray() &&
1726 node->getLeft()->getType().isVector() &&
1727 node->getOp() == glslang::EOpIndexDirect) {
1728 // This is essentially a hard-coded vector swizzle of size 1,
1729 // so short circuit the access-chain stuff with a swizzle.
1730 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001731 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001732 int dummySize;
1733 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1734 TranslateCoherent(node->getLeft()->getType()),
1735 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001736 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001737
1738 // Load through a block reference is performed with a dot operator that
1739 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1740 // do a load and reset the access chain.
1741 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1742 !node->getLeft()->getType().isArray() &&
1743 node->getOp() == glslang::EOpIndexDirectStruct)
1744 {
1745 spv::Id left = accessChainLoad(node->getLeft()->getType());
1746 builder.clearAccessChain();
1747 builder.setAccessChainLValue(left);
1748 }
1749
David Netoa901ffe2016-06-08 14:11:40 +01001750 int spvIndex = glslangIndex;
1751 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1752 node->getOp() == glslang::EOpIndexDirectStruct)
1753 {
1754 // This may be, e.g., an anonymous block-member selection, which generally need
1755 // index remapping due to hidden members in anonymous blocks.
1756 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1757 assert(remapper.size() > 0);
1758 spvIndex = remapper[glslangIndex];
1759 }
John Kessenichebb50532016-05-16 19:22:05 -06001760
David Netoa901ffe2016-06-08 14:11:40 +01001761 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001762 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001763
1764 // Add capabilities here for accessing PointSize and clip/cull distance.
1765 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001766 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001767 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001768 }
1769 }
1770 return false;
1771 case glslang::EOpIndexIndirect:
1772 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001773 // Array, matrix, or vector indirection with variable index.
1774 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001775 // matrices are arrays of vectors, so will also work for a matrix.
1776 // Will use the access chain's 'component' for variable index into a vector.
1777
1778 // This adapter is building access chains left to right.
1779 // Set up the access chain to the left.
1780 node->getLeft()->traverse(this);
1781
1782 // save it so that computing the right side doesn't trash it
1783 spv::Builder::AccessChain partial = builder.getAccessChain();
1784
1785 // compute the next index in the chain
1786 builder.clearAccessChain();
1787 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001788 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001789
John Kessenich5611c6d2018-04-05 11:25:02 -06001790 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1791
John Kessenich140f3df2015-06-26 16:58:36 -06001792 // restore the saved access chain
1793 builder.setAccessChain(partial);
1794
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001795 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1796 int dummySize;
1797 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1798 TranslateCoherent(node->getLeft()->getType()),
1799 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1800 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001801 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001802 }
1803 return false;
1804 case glslang::EOpVectorSwizzle:
1805 {
1806 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001807 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001808 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001809 int dummySize;
1810 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1811 TranslateCoherent(node->getLeft()->getType()),
1812 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001813 }
1814 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001815 case glslang::EOpMatrixSwizzle:
1816 logger->missingFunctionality("matrix swizzle");
1817 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001818 case glslang::EOpLogicalOr:
1819 case glslang::EOpLogicalAnd:
1820 {
1821
1822 // These may require short circuiting, but can sometimes be done as straight
1823 // binary operations. The right operand must be short circuited if it has
1824 // side effects, and should probably be if it is complex.
1825 if (isTrivial(node->getRight()->getAsTyped()))
1826 break; // handle below as a normal binary operation
1827 // otherwise, we need to do dynamic short circuiting on the right operand
1828 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1829 builder.clearAccessChain();
1830 builder.setAccessChainRValue(result);
1831 }
1832 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001833 default:
1834 break;
1835 }
1836
1837 // Assume generic binary op...
1838
John Kessenich32cfd492016-02-02 12:37:46 -07001839 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001840 builder.clearAccessChain();
1841 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001842 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001843
John Kessenich32cfd492016-02-02 12:37:46 -07001844 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001845 builder.clearAccessChain();
1846 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001847 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
John Kessenich32cfd492016-02-02 12:37:46 -07001849 // get result
John Kessenichead86222018-03-28 18:01:20 -06001850 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001851 TranslateNoContractionDecoration(node->getType().getQualifier()),
1852 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001853 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001854 convertGlslangToSpvType(node->getType()), left, right,
1855 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001856
John Kessenich50e57562015-12-21 21:21:11 -07001857 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001858 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001859 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001860 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001861 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001862 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001863 return false;
1864 }
John Kessenich140f3df2015-06-26 16:58:36 -06001865}
1866
1867bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1868{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001869 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001870
qining40887662016-04-03 22:20:42 -04001871 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1872 if (node->getType().getQualifier().isSpecConstant())
1873 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1874
John Kessenichfc51d282015-08-19 13:34:18 -06001875 spv::Id result = spv::NoResult;
1876
1877 // try texturing first
1878 result = createImageTextureFunctionCall(node);
1879 if (result != spv::NoResult) {
1880 builder.clearAccessChain();
1881 builder.setAccessChainRValue(result);
1882
1883 return false; // done with this node
1884 }
1885
1886 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001887
1888 if (node->getOp() == glslang::EOpArrayLength) {
1889 // Quite special; won't want to evaluate the operand.
1890
John Kessenich5611c6d2018-04-05 11:25:02 -06001891 // Currently, the front-end does not allow .length() on an array until it is sized,
1892 // except for the last block membeor of an SSBO.
1893 // TODO: If this changes, link-time sized arrays might show up here, and need their
1894 // size extracted.
1895
John Kessenichc9a80832015-09-12 12:17:44 -06001896 // Normal .length() would have been constant folded by the front-end.
1897 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001898 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001899
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001900 spv::Id length;
1901 if (node->getOperand()->getType().isCoopMat()) {
1902 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1903
1904 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1905 assert(builder.isCooperativeMatrixType(typeId));
1906
1907 length = builder.createCooperativeMatrixLength(typeId);
1908 } else {
1909 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1910 block->traverse(this);
1911 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1912 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1913 }
John Kessenichc9a80832015-09-12 12:17:44 -06001914
John Kessenich8c869672018-11-28 07:01:37 -07001915 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1916 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1917 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001918 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1919 if (builder.isInSpecConstCodeGenMode()) {
1920 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1921 } else {
1922 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1923 }
1924 }
John Kessenich8c869672018-11-28 07:01:37 -07001925
John Kessenichc9a80832015-09-12 12:17:44 -06001926 builder.clearAccessChain();
1927 builder.setAccessChainRValue(length);
1928
1929 return false;
1930 }
1931
John Kessenichfc51d282015-08-19 13:34:18 -06001932 // Start by evaluating the operand
1933
John Kessenich8c8505c2016-07-26 12:50:38 -06001934 // Does it need a swizzle inversion? If so, evaluation is inverted;
1935 // operate first on the swizzle base, then apply the swizzle.
1936 spv::Id invertedType = spv::NoType;
1937 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1938 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1939 invertedType = getInvertedSwizzleType(*node->getOperand());
1940
John Kessenich140f3df2015-06-26 16:58:36 -06001941 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001942 if (invertedType != spv::NoType)
1943 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1944 else
1945 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001946
Rex Xufc618912015-09-09 16:42:49 +08001947 spv::Id operand = spv::NoResult;
1948
1949 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1950 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001951 node->getOp() == glslang::EOpAtomicCounter ||
1952 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001953 operand = builder.accessChainGetLValue(); // Special case l-value operands
1954 else
John Kessenich32cfd492016-02-02 12:37:46 -07001955 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001956
John Kessenichead86222018-03-28 18:01:20 -06001957 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001958 TranslateNoContractionDecoration(node->getType().getQualifier()),
1959 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001960
1961 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001962 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001963 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001964
1965 // if not, then possibly an operation
1966 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001967 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001968
1969 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001970 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001971 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001972 builder.addDecoration(result, decorations.nonUniform);
1973 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001974
John Kessenich140f3df2015-06-26 16:58:36 -06001975 builder.clearAccessChain();
1976 builder.setAccessChainRValue(result);
1977
1978 return false; // done with this node
1979 }
1980
1981 // it must be a special case, check...
1982 switch (node->getOp()) {
1983 case glslang::EOpPostIncrement:
1984 case glslang::EOpPostDecrement:
1985 case glslang::EOpPreIncrement:
1986 case glslang::EOpPreDecrement:
1987 {
1988 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001989 spv::Id one = 0;
1990 if (node->getBasicType() == glslang::EbtFloat)
1991 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001992 else if (node->getBasicType() == glslang::EbtDouble)
1993 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001994 else if (node->getBasicType() == glslang::EbtFloat16)
1995 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001996 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1997 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001998 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1999 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002000 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2001 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002002 else
2003 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002004 glslang::TOperator op;
2005 if (node->getOp() == glslang::EOpPreIncrement ||
2006 node->getOp() == glslang::EOpPostIncrement)
2007 op = glslang::EOpAdd;
2008 else
2009 op = glslang::EOpSub;
2010
John Kessenichead86222018-03-28 18:01:20 -06002011 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002012 convertGlslangToSpvType(node->getType()), operand, one,
2013 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002014 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002015
2016 // The result of operation is always stored, but conditionally the
2017 // consumed result. The consumed result is always an r-value.
2018 builder.accessChainStore(result);
2019 builder.clearAccessChain();
2020 if (node->getOp() == glslang::EOpPreIncrement ||
2021 node->getOp() == glslang::EOpPreDecrement)
2022 builder.setAccessChainRValue(result);
2023 else
2024 builder.setAccessChainRValue(operand);
2025 }
2026
2027 return false;
2028
2029 case glslang::EOpEmitStreamVertex:
2030 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2031 return false;
2032 case glslang::EOpEndStreamPrimitive:
2033 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2034 return false;
2035
2036 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002037 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002038 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002039 }
John Kessenich140f3df2015-06-26 16:58:36 -06002040}
2041
2042bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2043{
qining27e04a02016-04-14 16:40:20 -04002044 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2045 if (node->getType().getQualifier().isSpecConstant())
2046 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2047
John Kessenichfc51d282015-08-19 13:34:18 -06002048 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002049 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2050 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002051
2052 // try texturing
2053 result = createImageTextureFunctionCall(node);
2054 if (result != spv::NoResult) {
2055 builder.clearAccessChain();
2056 builder.setAccessChainRValue(result);
2057
2058 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002059 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002060#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002061 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002062#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002063 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002064 // "imageStore" is a special case, which has no result
2065 return false;
2066 }
John Kessenichfc51d282015-08-19 13:34:18 -06002067
John Kessenich140f3df2015-06-26 16:58:36 -06002068 glslang::TOperator binOp = glslang::EOpNull;
2069 bool reduceComparison = true;
2070 bool isMatrix = false;
2071 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002072 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002073
2074 assert(node->getOp());
2075
John Kessenichf6640762016-08-01 19:44:00 -06002076 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002077
2078 switch (node->getOp()) {
2079 case glslang::EOpSequence:
2080 {
2081 if (preVisit)
2082 ++sequenceDepth;
2083 else
2084 --sequenceDepth;
2085
2086 if (sequenceDepth == 1) {
2087 // If this is the parent node of all the functions, we want to see them
2088 // early, so all call points have actual SPIR-V functions to reference.
2089 // In all cases, still let the traverser visit the children for us.
2090 makeFunctions(node->getAsAggregate()->getSequence());
2091
John Kessenich6fccb3c2016-09-19 16:01:41 -06002092 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002093 // anything else gets there, so visit out of order, doing them all now.
2094 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2095
John Kessenich6a60c2f2016-12-08 21:01:59 -07002096 // 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 -06002097 // so do them manually.
2098 visitFunctions(node->getAsAggregate()->getSequence());
2099
2100 return false;
2101 }
2102
2103 return true;
2104 }
2105 case glslang::EOpLinkerObjects:
2106 {
2107 if (visit == glslang::EvPreVisit)
2108 linkageOnly = true;
2109 else
2110 linkageOnly = false;
2111
2112 return true;
2113 }
2114 case glslang::EOpComma:
2115 {
2116 // processing from left to right naturally leaves the right-most
2117 // lying around in the access chain
2118 glslang::TIntermSequence& glslangOperands = node->getSequence();
2119 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2120 glslangOperands[i]->traverse(this);
2121
2122 return false;
2123 }
2124 case glslang::EOpFunction:
2125 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002126 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002127 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002128 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002129 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002130 } else {
2131 handleFunctionEntry(node);
2132 }
2133 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002134 if (inEntryPoint)
2135 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002136 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002137 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002138 }
2139
2140 return true;
2141 case glslang::EOpParameters:
2142 // Parameters will have been consumed by EOpFunction processing, but not
2143 // the body, so we still visited the function node's children, making this
2144 // child redundant.
2145 return false;
2146 case glslang::EOpFunctionCall:
2147 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002148 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002149 if (node->isUserDefined())
2150 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002151 // 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 -07002152 if (result) {
2153 builder.clearAccessChain();
2154 builder.setAccessChainRValue(result);
2155 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002156 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002157
2158 return false;
2159 }
2160 case glslang::EOpConstructMat2x2:
2161 case glslang::EOpConstructMat2x3:
2162 case glslang::EOpConstructMat2x4:
2163 case glslang::EOpConstructMat3x2:
2164 case glslang::EOpConstructMat3x3:
2165 case glslang::EOpConstructMat3x4:
2166 case glslang::EOpConstructMat4x2:
2167 case glslang::EOpConstructMat4x3:
2168 case glslang::EOpConstructMat4x4:
2169 case glslang::EOpConstructDMat2x2:
2170 case glslang::EOpConstructDMat2x3:
2171 case glslang::EOpConstructDMat2x4:
2172 case glslang::EOpConstructDMat3x2:
2173 case glslang::EOpConstructDMat3x3:
2174 case glslang::EOpConstructDMat3x4:
2175 case glslang::EOpConstructDMat4x2:
2176 case glslang::EOpConstructDMat4x3:
2177 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002178 case glslang::EOpConstructIMat2x2:
2179 case glslang::EOpConstructIMat2x3:
2180 case glslang::EOpConstructIMat2x4:
2181 case glslang::EOpConstructIMat3x2:
2182 case glslang::EOpConstructIMat3x3:
2183 case glslang::EOpConstructIMat3x4:
2184 case glslang::EOpConstructIMat4x2:
2185 case glslang::EOpConstructIMat4x3:
2186 case glslang::EOpConstructIMat4x4:
2187 case glslang::EOpConstructUMat2x2:
2188 case glslang::EOpConstructUMat2x3:
2189 case glslang::EOpConstructUMat2x4:
2190 case glslang::EOpConstructUMat3x2:
2191 case glslang::EOpConstructUMat3x3:
2192 case glslang::EOpConstructUMat3x4:
2193 case glslang::EOpConstructUMat4x2:
2194 case glslang::EOpConstructUMat4x3:
2195 case glslang::EOpConstructUMat4x4:
2196 case glslang::EOpConstructBMat2x2:
2197 case glslang::EOpConstructBMat2x3:
2198 case glslang::EOpConstructBMat2x4:
2199 case glslang::EOpConstructBMat3x2:
2200 case glslang::EOpConstructBMat3x3:
2201 case glslang::EOpConstructBMat3x4:
2202 case glslang::EOpConstructBMat4x2:
2203 case glslang::EOpConstructBMat4x3:
2204 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002205 case glslang::EOpConstructF16Mat2x2:
2206 case glslang::EOpConstructF16Mat2x3:
2207 case glslang::EOpConstructF16Mat2x4:
2208 case glslang::EOpConstructF16Mat3x2:
2209 case glslang::EOpConstructF16Mat3x3:
2210 case glslang::EOpConstructF16Mat3x4:
2211 case glslang::EOpConstructF16Mat4x2:
2212 case glslang::EOpConstructF16Mat4x3:
2213 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002214 isMatrix = true;
2215 // fall through
2216 case glslang::EOpConstructFloat:
2217 case glslang::EOpConstructVec2:
2218 case glslang::EOpConstructVec3:
2219 case glslang::EOpConstructVec4:
2220 case glslang::EOpConstructDouble:
2221 case glslang::EOpConstructDVec2:
2222 case glslang::EOpConstructDVec3:
2223 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002224 case glslang::EOpConstructFloat16:
2225 case glslang::EOpConstructF16Vec2:
2226 case glslang::EOpConstructF16Vec3:
2227 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002228 case glslang::EOpConstructBool:
2229 case glslang::EOpConstructBVec2:
2230 case glslang::EOpConstructBVec3:
2231 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002232 case glslang::EOpConstructInt8:
2233 case glslang::EOpConstructI8Vec2:
2234 case glslang::EOpConstructI8Vec3:
2235 case glslang::EOpConstructI8Vec4:
2236 case glslang::EOpConstructUint8:
2237 case glslang::EOpConstructU8Vec2:
2238 case glslang::EOpConstructU8Vec3:
2239 case glslang::EOpConstructU8Vec4:
2240 case glslang::EOpConstructInt16:
2241 case glslang::EOpConstructI16Vec2:
2242 case glslang::EOpConstructI16Vec3:
2243 case glslang::EOpConstructI16Vec4:
2244 case glslang::EOpConstructUint16:
2245 case glslang::EOpConstructU16Vec2:
2246 case glslang::EOpConstructU16Vec3:
2247 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002248 case glslang::EOpConstructInt:
2249 case glslang::EOpConstructIVec2:
2250 case glslang::EOpConstructIVec3:
2251 case glslang::EOpConstructIVec4:
2252 case glslang::EOpConstructUint:
2253 case glslang::EOpConstructUVec2:
2254 case glslang::EOpConstructUVec3:
2255 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002256 case glslang::EOpConstructInt64:
2257 case glslang::EOpConstructI64Vec2:
2258 case glslang::EOpConstructI64Vec3:
2259 case glslang::EOpConstructI64Vec4:
2260 case glslang::EOpConstructUint64:
2261 case glslang::EOpConstructU64Vec2:
2262 case glslang::EOpConstructU64Vec3:
2263 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002264 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002265 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002266 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002267 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002268 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002269 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002270 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002271 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002272 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002273 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002274 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002275 else if (node->getOp() == glslang::EOpConstructStruct ||
2276 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2277 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002278 std::vector<spv::Id> constituents;
2279 for (int c = 0; c < (int)arguments.size(); ++c)
2280 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002281 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002282 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002283 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002284 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002285 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002286
2287 builder.clearAccessChain();
2288 builder.setAccessChainRValue(constructed);
2289
2290 return false;
2291 }
2292
2293 // These six are component-wise compares with component-wise results.
2294 // Forward on to createBinaryOperation(), requesting a vector result.
2295 case glslang::EOpLessThan:
2296 case glslang::EOpGreaterThan:
2297 case glslang::EOpLessThanEqual:
2298 case glslang::EOpGreaterThanEqual:
2299 case glslang::EOpVectorEqual:
2300 case glslang::EOpVectorNotEqual:
2301 {
2302 // Map the operation to a binary
2303 binOp = node->getOp();
2304 reduceComparison = false;
2305 switch (node->getOp()) {
2306 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2307 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2308 default: binOp = node->getOp(); break;
2309 }
2310
2311 break;
2312 }
2313 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002314 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002315 binOp = glslang::EOpMul;
2316 break;
2317 case glslang::EOpOuterProduct:
2318 // two vectors multiplied to make a matrix
2319 binOp = glslang::EOpOuterProduct;
2320 break;
2321 case glslang::EOpDot:
2322 {
qining25262b32016-05-06 17:25:16 -04002323 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002324 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002325 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002326 binOp = glslang::EOpMul;
2327 break;
2328 }
2329 case glslang::EOpMod:
2330 // when an aggregate, this is the floating-point mod built-in function,
2331 // which can be emitted by the one in createBinaryOperation()
2332 binOp = glslang::EOpMod;
2333 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002334 case glslang::EOpEmitVertex:
2335 case glslang::EOpEndPrimitive:
2336 case glslang::EOpBarrier:
2337 case glslang::EOpMemoryBarrier:
2338 case glslang::EOpMemoryBarrierAtomicCounter:
2339 case glslang::EOpMemoryBarrierBuffer:
2340 case glslang::EOpMemoryBarrierImage:
2341 case glslang::EOpMemoryBarrierShared:
2342 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002343 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002344 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002345 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002346 case glslang::EOpWorkgroupMemoryBarrier:
2347 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002348 case glslang::EOpSubgroupBarrier:
2349 case glslang::EOpSubgroupMemoryBarrier:
2350 case glslang::EOpSubgroupMemoryBarrierBuffer:
2351 case glslang::EOpSubgroupMemoryBarrierImage:
2352 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002353 noReturnValue = true;
2354 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2355 break;
2356
Jeff Bolz36831c92018-09-05 10:11:41 -05002357 case glslang::EOpAtomicStore:
2358 noReturnValue = true;
2359 // fallthrough
2360 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002361 case glslang::EOpAtomicAdd:
2362 case glslang::EOpAtomicMin:
2363 case glslang::EOpAtomicMax:
2364 case glslang::EOpAtomicAnd:
2365 case glslang::EOpAtomicOr:
2366 case glslang::EOpAtomicXor:
2367 case glslang::EOpAtomicExchange:
2368 case glslang::EOpAtomicCompSwap:
2369 atomic = true;
2370 break;
2371
John Kessenich0d0c6d32017-07-23 16:08:26 -06002372 case glslang::EOpAtomicCounterAdd:
2373 case glslang::EOpAtomicCounterSubtract:
2374 case glslang::EOpAtomicCounterMin:
2375 case glslang::EOpAtomicCounterMax:
2376 case glslang::EOpAtomicCounterAnd:
2377 case glslang::EOpAtomicCounterOr:
2378 case glslang::EOpAtomicCounterXor:
2379 case glslang::EOpAtomicCounterExchange:
2380 case glslang::EOpAtomicCounterCompSwap:
2381 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2382 builder.addCapability(spv::CapabilityAtomicStorageOps);
2383 atomic = true;
2384 break;
2385
Chao Chen3c366992018-09-19 11:41:59 -07002386#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002387 case glslang::EOpIgnoreIntersectionNV:
2388 case glslang::EOpTerminateRayNV:
2389 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002390 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002391 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2392 noReturnValue = true;
2393 break;
2394#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002395 case glslang::EOpCooperativeMatrixLoad:
2396 case glslang::EOpCooperativeMatrixStore:
2397 noReturnValue = true;
2398 break;
Chao Chen3c366992018-09-19 11:41:59 -07002399
John Kessenich140f3df2015-06-26 16:58:36 -06002400 default:
2401 break;
2402 }
2403
2404 //
2405 // See if it maps to a regular operation.
2406 //
John Kessenich140f3df2015-06-26 16:58:36 -06002407 if (binOp != glslang::EOpNull) {
2408 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2409 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2410 assert(left && right);
2411
2412 builder.clearAccessChain();
2413 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002414 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002415
2416 builder.clearAccessChain();
2417 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002418 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002419
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002420 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002421 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002422 TranslateNoContractionDecoration(node->getType().getQualifier()),
2423 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002424 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002425 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002426 left->getType().getBasicType(), reduceComparison);
2427
2428 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002429 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002430 builder.clearAccessChain();
2431 builder.setAccessChainRValue(result);
2432
2433 return false;
2434 }
2435
John Kessenich426394d2015-07-23 10:22:48 -06002436 //
2437 // Create the list of operands.
2438 //
John Kessenich140f3df2015-06-26 16:58:36 -06002439 glslang::TIntermSequence& glslangOperands = node->getSequence();
2440 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002441 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002442 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002443 // special case l-value operands; there are just a few
2444 bool lvalue = false;
2445 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002446 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002447 case glslang::EOpModf:
2448 if (arg == 1)
2449 lvalue = true;
2450 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002451 case glslang::EOpInterpolateAtSample:
2452 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002453#ifdef AMD_EXTENSIONS
2454 case glslang::EOpInterpolateAtVertex:
2455#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002456 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002457 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002458
2459 // Does it need a swizzle inversion? If so, evaluation is inverted;
2460 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002461 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002462 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2463 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2464 }
Rex Xu7a26c172015-12-08 17:12:09 +08002465 break;
Rex Xud4782c12015-09-06 16:30:11 +08002466 case glslang::EOpAtomicAdd:
2467 case glslang::EOpAtomicMin:
2468 case glslang::EOpAtomicMax:
2469 case glslang::EOpAtomicAnd:
2470 case glslang::EOpAtomicOr:
2471 case glslang::EOpAtomicXor:
2472 case glslang::EOpAtomicExchange:
2473 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002474 case glslang::EOpAtomicLoad:
2475 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002476 case glslang::EOpAtomicCounterAdd:
2477 case glslang::EOpAtomicCounterSubtract:
2478 case glslang::EOpAtomicCounterMin:
2479 case glslang::EOpAtomicCounterMax:
2480 case glslang::EOpAtomicCounterAnd:
2481 case glslang::EOpAtomicCounterOr:
2482 case glslang::EOpAtomicCounterXor:
2483 case glslang::EOpAtomicCounterExchange:
2484 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002485 if (arg == 0)
2486 lvalue = true;
2487 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002488 case glslang::EOpAddCarry:
2489 case glslang::EOpSubBorrow:
2490 if (arg == 2)
2491 lvalue = true;
2492 break;
2493 case glslang::EOpUMulExtended:
2494 case glslang::EOpIMulExtended:
2495 if (arg >= 2)
2496 lvalue = true;
2497 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002498 case glslang::EOpCooperativeMatrixLoad:
2499 if (arg == 0 || arg == 1)
2500 lvalue = true;
2501 break;
2502 case glslang::EOpCooperativeMatrixStore:
2503 if (arg == 1)
2504 lvalue = true;
2505 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002506 default:
2507 break;
2508 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002509 builder.clearAccessChain();
2510 if (invertedType != spv::NoType && arg == 0)
2511 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2512 else
2513 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002514
2515 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2516 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2517
2518 if (arg == 1) {
2519 // fold "element" parameter into the access chain
2520 spv::Builder::AccessChain save = builder.getAccessChain();
2521 builder.clearAccessChain();
2522 glslangOperands[2]->traverse(this);
2523
2524 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2525
2526 builder.setAccessChain(save);
2527
2528 // Point to the first element of the array.
2529 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002530 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002531
2532 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2533 unsigned int alignment = builder.getAccessChain().alignment;
2534
2535 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2536 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2537 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2538 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2539 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2540 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2541 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2542 }
2543
2544 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2545
2546 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2547 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2548 }
2549
2550 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2551 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2552 }
2553 } else if (arg == 2) {
2554 continue;
2555 }
2556 }
2557
John Kessenich140f3df2015-06-26 16:58:36 -06002558 if (lvalue)
2559 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002560 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002561 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002562 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002563 }
John Kessenich140f3df2015-06-26 16:58:36 -06002564 }
John Kessenich426394d2015-07-23 10:22:48 -06002565
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002566 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002567 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2568 std::vector<spv::IdImmediate> idImmOps;
2569
2570 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2571 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2572 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2573 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2574 // get the pointee type
2575 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2576 assert(builder.isCooperativeMatrixType(typeId));
2577 // do the op
2578 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2579 // store the result to the pointer (out param 'm')
2580 builder.createStore(result, operands[0]);
2581 result = 0;
2582 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2583 std::vector<spv::IdImmediate> idImmOps;
2584
2585 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2586 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2587 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2588 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2589 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2590
2591 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2592 result = 0;
2593 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002594 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002595 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002596 } else {
2597 // Pass through to generic operations.
2598 switch (glslangOperands.size()) {
2599 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002600 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002601 break;
2602 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002603 {
2604 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002605 TranslateNoContractionDecoration(node->getType().getQualifier()),
2606 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002607 result = createUnaryOperation(
2608 node->getOp(), decorations,
2609 resultType(), operands.front(),
2610 glslangOperands[0]->getAsTyped()->getBasicType());
2611 }
John Kessenich426394d2015-07-23 10:22:48 -06002612 break;
2613 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002614 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002615 break;
2616 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002617 if (invertedType)
2618 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002619 }
2620
2621 if (noReturnValue)
2622 return false;
2623
2624 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002625 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002626 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002627 } else {
2628 builder.clearAccessChain();
2629 builder.setAccessChainRValue(result);
2630 return false;
2631 }
2632}
2633
John Kessenich433e9ff2017-01-26 20:31:11 -07002634// This path handles both if-then-else and ?:
2635// The if-then-else has a node type of void, while
2636// ?: has either a void or a non-void node type
2637//
2638// Leaving the result, when not void:
2639// GLSL only has r-values as the result of a :?, but
2640// if we have an l-value, that can be more efficient if it will
2641// become the base of a complex r-value expression, because the
2642// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002643bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2644{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002645 // see if OpSelect can handle it
2646 const auto isOpSelectable = [&]() {
2647 if (node->getBasicType() == glslang::EbtVoid)
2648 return false;
2649 // OpSelect can do all other types starting with SPV 1.4
2650 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2651 // pre-1.4, only scalars and vectors can be handled
2652 if ((!node->getType().isScalar() && !node->getType().isVector()))
2653 return false;
2654 }
2655 return true;
2656 };
2657
John Kessenich4bee5312018-02-20 21:29:05 -07002658 // See if it simple and safe, or required, to execute both sides.
2659 // Crucially, side effects must be either semantically required or avoided,
2660 // and there are performance trade-offs.
2661 // Return true if required or a good idea (and safe) to execute both sides,
2662 // false otherwise.
2663 const auto bothSidesPolicy = [&]() -> bool {
2664 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002665 if (node->getTrueBlock() == nullptr ||
2666 node->getFalseBlock() == nullptr)
2667 return false;
2668
John Kessenich4bee5312018-02-20 21:29:05 -07002669 // required? (unless we write additional code to look for side effects
2670 // and make performance trade-offs if none are present)
2671 if (!node->getShortCircuit())
2672 return true;
2673
2674 // if not required to execute both, decide based on performance/practicality...
2675
John Kessenich0c1e71a2019-01-10 18:23:06 +07002676 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002677 return false;
2678
John Kessenich433e9ff2017-01-26 20:31:11 -07002679 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2680 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2681
2682 // return true if a single operand to ? : is okay for OpSelect
2683 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002684 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002685 };
2686
2687 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2688 operandOkay(node->getFalseBlock()->getAsTyped());
2689 };
2690
John Kessenich4bee5312018-02-20 21:29:05 -07002691 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2692 // emit the condition before doing anything with selection
2693 node->getCondition()->traverse(this);
2694 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2695
2696 // Find a way of executing both sides and selecting the right result.
2697 const auto executeBothSides = [&]() -> void {
2698 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002699 node->getTrueBlock()->traverse(this);
2700 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2701 node->getFalseBlock()->traverse(this);
2702 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2703
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002704 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002705
John Kessenich4bee5312018-02-20 21:29:05 -07002706 // done if void
2707 if (node->getBasicType() == glslang::EbtVoid)
2708 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002709
John Kessenich4bee5312018-02-20 21:29:05 -07002710 // emit code to select between trueValue and falseValue
2711
2712 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002713 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002714 // Emit OpSelect for this selection.
2715
2716 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002717 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2718 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002719 condition = builder.smearScalar(spv::NoPrecision, condition,
2720 builder.makeVectorType(builder.makeBoolType(),
2721 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002722 }
John Kessenich4bee5312018-02-20 21:29:05 -07002723
2724 // OpSelect
2725 result = builder.createTriOp(spv::OpSelect,
2726 convertGlslangToSpvType(node->getType()), condition,
2727 trueValue, falseValue);
2728
2729 builder.clearAccessChain();
2730 builder.setAccessChainRValue(result);
2731 } else {
2732 // We need control flow to select the result.
2733 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2734 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2735
2736 // Selection control:
2737 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2738
2739 // make an "if" based on the value created by the condition
2740 spv::Builder::If ifBuilder(condition, control, builder);
2741
2742 // emit the "then" statement
2743 builder.createStore(trueValue, result);
2744 ifBuilder.makeBeginElse();
2745 // emit the "else" statement
2746 builder.createStore(falseValue, result);
2747
2748 // finish off the control flow
2749 ifBuilder.makeEndIf();
2750
2751 builder.clearAccessChain();
2752 builder.setAccessChainLValue(result);
2753 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002754 };
2755
John Kessenich4bee5312018-02-20 21:29:05 -07002756 // Execute the one side needed, as per the condition
2757 const auto executeOneSide = [&]() {
2758 // Always emit control flow.
2759 if (node->getBasicType() != glslang::EbtVoid)
2760 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002761
John Kessenich4bee5312018-02-20 21:29:05 -07002762 // Selection control:
2763 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2764
2765 // make an "if" based on the value created by the condition
2766 spv::Builder::If ifBuilder(condition, control, builder);
2767
2768 // emit the "then" statement
2769 if (node->getTrueBlock() != nullptr) {
2770 node->getTrueBlock()->traverse(this);
2771 if (result != spv::NoResult)
2772 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2773 }
2774
2775 if (node->getFalseBlock() != nullptr) {
2776 ifBuilder.makeBeginElse();
2777 // emit the "else" statement
2778 node->getFalseBlock()->traverse(this);
2779 if (result != spv::NoResult)
2780 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2781 }
2782
2783 // finish off the control flow
2784 ifBuilder.makeEndIf();
2785
2786 if (result != spv::NoResult) {
2787 builder.clearAccessChain();
2788 builder.setAccessChainLValue(result);
2789 }
2790 };
2791
2792 // Try for OpSelect (or a requirement to execute both sides)
2793 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002794 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2795 if (node->getType().getQualifier().isSpecConstant())
2796 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002797 executeBothSides();
2798 } else
2799 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002800
2801 return false;
2802}
2803
2804bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2805{
2806 // emit and get the condition before doing anything with switch
2807 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002808 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002809
Rex Xu57e65922017-07-04 23:23:40 +08002810 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002811 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002812
John Kessenich140f3df2015-06-26 16:58:36 -06002813 // browse the children to sort out code segments
2814 int defaultSegment = -1;
2815 std::vector<TIntermNode*> codeSegments;
2816 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2817 std::vector<int> caseValues;
2818 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2819 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2820 TIntermNode* child = *c;
2821 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002822 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002823 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002824 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002825 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2826 } else
2827 codeSegments.push_back(child);
2828 }
2829
qining25262b32016-05-06 17:25:16 -04002830 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002831 // statements between the last case and the end of the switch statement
2832 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2833 (int)codeSegments.size() == defaultSegment)
2834 codeSegments.push_back(nullptr);
2835
2836 // make the switch statement
2837 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002838 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002839
2840 // emit all the code in the segments
2841 breakForLoop.push(false);
2842 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2843 builder.nextSwitchSegment(segmentBlocks, s);
2844 if (codeSegments[s])
2845 codeSegments[s]->traverse(this);
2846 else
2847 builder.addSwitchBreak();
2848 }
2849 breakForLoop.pop();
2850
2851 builder.endSwitch(segmentBlocks);
2852
2853 return false;
2854}
2855
2856void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2857{
2858 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002859 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002860
2861 builder.clearAccessChain();
2862 builder.setAccessChainRValue(constant);
2863}
2864
2865bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2866{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002867 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002868 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002869
2870 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002871 std::vector<unsigned int> operands;
2872 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002873
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002874 // Spec requires back edges to target header blocks, and every header block
2875 // must dominate its merge block. Make a header block first to ensure these
2876 // conditions are met. By definition, it will contain OpLoopMerge, followed
2877 // by a block-ending branch. But we don't want to put any other body/test
2878 // instructions in it, since the body/test may have arbitrary instructions,
2879 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002880 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002881 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002882 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002883 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002884 spv::Block& test = builder.makeNewBlock();
2885 builder.createBranch(&test);
2886
2887 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002888 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002889 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002890 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2891
2892 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002893 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002894 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002895 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002896 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002897 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002898
2899 builder.setBuildPoint(&blocks.continue_target);
2900 if (node->getTerminal())
2901 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002902 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002903 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002904 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002905 builder.createBranch(&blocks.body);
2906
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002907 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002908 builder.setBuildPoint(&blocks.body);
2909 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002910 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002911 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002912 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002913
2914 builder.setBuildPoint(&blocks.continue_target);
2915 if (node->getTerminal())
2916 node->getTerminal()->traverse(this);
2917 if (node->getTest()) {
2918 node->getTest()->traverse(this);
2919 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002920 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002921 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002922 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002923 // TODO: unless there was a break/return/discard instruction
2924 // somewhere in the body, this is an infinite loop, so we should
2925 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002926 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002927 }
John Kessenich140f3df2015-06-26 16:58:36 -06002928 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002929 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002930 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002931 return false;
2932}
2933
2934bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2935{
2936 if (node->getExpression())
2937 node->getExpression()->traverse(this);
2938
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002939 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002940
John Kessenich140f3df2015-06-26 16:58:36 -06002941 switch (node->getFlowOp()) {
2942 case glslang::EOpKill:
2943 builder.makeDiscard();
2944 break;
2945 case glslang::EOpBreak:
2946 if (breakForLoop.top())
2947 builder.createLoopExit();
2948 else
2949 builder.addSwitchBreak();
2950 break;
2951 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002952 builder.createLoopContinue();
2953 break;
2954 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002955 if (node->getExpression()) {
2956 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2957 spv::Id returnId = accessChainLoad(glslangReturnType);
2958 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2959 builder.clearAccessChain();
2960 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2961 builder.setAccessChainLValue(copyId);
2962 multiTypeStore(glslangReturnType, returnId);
2963 returnId = builder.createLoad(copyId);
2964 }
2965 builder.makeReturn(false, returnId);
2966 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002967 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002968
2969 builder.clearAccessChain();
2970 break;
2971
2972 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002973 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975 }
2976
2977 return false;
2978}
2979
2980spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2981{
qining25262b32016-05-06 17:25:16 -04002982 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002983 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002984 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002985 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002986 spv::Id result = createSpvConstant(*node);
2987 if (result != spv::NoResult)
2988 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002989 }
2990
2991 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002992 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002993 spv::Id spvType = convertGlslangToSpvType(node->getType());
2994
Rex Xucabbb782017-03-24 13:41:14 +08002995 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2996 node->getType().containsBasicType(glslang::EbtInt16) ||
2997 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002998 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002999 switch (storageClass) {
3000 case spv::StorageClassInput:
3001 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003002 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003003 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003004 break;
3005 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003006 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003007 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003008 break;
3009 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003010 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003011 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3012 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003013 else
3014 builder.addCapability(spv::CapabilityStorageUniform16);
3015 break;
3016 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003017 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003018 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3019 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3020 break;
3021 default:
3022 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003023 }
3024 }
Rex Xuf89ad982017-04-07 23:22:33 +08003025
John Kessenich312dcfb2018-07-03 13:19:51 -06003026 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3027 node->getType().containsBasicType(glslang::EbtUint8);
3028 if (contains8BitType) {
3029 if (storageClass == spv::StorageClassPushConstant) {
3030 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3031 builder.addCapability(spv::CapabilityStoragePushConstant8);
3032 } else if (storageClass == spv::StorageClassUniform) {
3033 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3034 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003035 } else if (storageClass == spv::StorageClassStorageBuffer) {
3036 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3037 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003038 }
3039 }
3040
John Kessenich140f3df2015-06-26 16:58:36 -06003041 const char* name = node->getName().c_str();
3042 if (glslang::IsAnonymous(name))
3043 name = "";
3044
3045 return builder.createVariable(storageClass, spvType, name);
3046}
3047
3048// Return type Id of the sampled type.
3049spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3050{
3051 switch (sampler.type) {
3052 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003053#ifdef AMD_EXTENSIONS
3054 case glslang::EbtFloat16:
3055 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3056 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3057 return builder.makeFloatType(16);
3058#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003059 case glslang::EbtInt: return builder.makeIntType(32);
3060 case glslang::EbtUint: return builder.makeUintType(32);
3061 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003062 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003063 return builder.makeFloatType(32);
3064 }
3065}
3066
John Kessenich8c8505c2016-07-26 12:50:38 -06003067// If node is a swizzle operation, return the type that should be used if
3068// the swizzle base is first consumed by another operation, before the swizzle
3069// is applied.
3070spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3071{
John Kessenichecba76f2017-01-06 00:34:48 -07003072 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003073 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3074 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3075 else
3076 return spv::NoType;
3077}
3078
3079// When inverting a swizzle with a parent op, this function
3080// will apply the swizzle operation to a completed parent operation.
3081spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3082{
3083 std::vector<unsigned> swizzle;
3084 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3085 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3086}
3087
John Kessenich8c8505c2016-07-26 12:50:38 -06003088// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3089void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3090{
3091 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3092 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3093 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3094}
3095
John Kessenich3ac051e2015-12-20 11:29:16 -07003096// Convert from a glslang type to an SPV type, by calling into a
3097// recursive version of this function. This establishes the inherited
3098// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003099spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003100{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003101 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003102}
3103
3104// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003105// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003106// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003107spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003108 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3109 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003110{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003111 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003112
3113 switch (type.getBasicType()) {
3114 case glslang::EbtVoid:
3115 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003116 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003117 break;
3118 case glslang::EbtFloat:
3119 spvType = builder.makeFloatType(32);
3120 break;
3121 case glslang::EbtDouble:
3122 spvType = builder.makeFloatType(64);
3123 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003124 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003125 spvType = builder.makeFloatType(16);
3126 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003128 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3129 // a 32-bit int where non-0 means true.
3130 if (explicitLayout != glslang::ElpNone)
3131 spvType = builder.makeUintType(32);
3132 else
3133 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003134 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003135 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003136 spvType = builder.makeIntType(8);
3137 break;
3138 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003139 spvType = builder.makeUintType(8);
3140 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003141 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003142 spvType = builder.makeIntType(16);
3143 break;
3144 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003145 spvType = builder.makeUintType(16);
3146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003147 case glslang::EbtInt:
3148 spvType = builder.makeIntType(32);
3149 break;
3150 case glslang::EbtUint:
3151 spvType = builder.makeUintType(32);
3152 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003153 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003154 spvType = builder.makeIntType(64);
3155 break;
3156 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003157 spvType = builder.makeUintType(64);
3158 break;
John Kessenich426394d2015-07-23 10:22:48 -06003159 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003160 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003161 spvType = builder.makeUintType(32);
3162 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003163#ifdef NV_EXTENSIONS
3164 case glslang::EbtAccStructNV:
3165 spvType = builder.makeAccelerationStructureNVType();
3166 break;
3167#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003168 case glslang::EbtSampler:
3169 {
3170 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003171 if (sampler.sampler) {
3172 // pure sampler
3173 spvType = builder.makeSamplerType();
3174 } else {
3175 // an image is present, make its type
3176 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3177 sampler.image ? 2 : 1, TranslateImageFormat(type));
3178 if (sampler.combined) {
3179 // already has both image and sampler, make the combined type
3180 spvType = builder.makeSampledImageType(spvType);
3181 }
John Kessenich55e7d112015-11-15 21:33:39 -07003182 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003183 }
John Kessenich140f3df2015-06-26 16:58:36 -06003184 break;
3185 case glslang::EbtStruct:
3186 case glslang::EbtBlock:
3187 {
3188 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003189 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003190
3191 // Try to share structs for different layouts, but not yet for other
3192 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003193 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003194 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003195 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197
3198 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003199 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003200 memberRemapper[glslangMembers].resize(glslangMembers->size());
3201 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003202 }
3203 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003204 case glslang::EbtReference:
3205 {
3206 // Make the forward pointer, then recurse to convert the structure type, then
3207 // patch up the forward pointer with a real pointer type.
3208 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3209 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3210 forwardPointers[type.getReferentType()] = forwardId;
3211 }
3212 spvType = forwardPointers[type.getReferentType()];
3213 if (!forwardReferenceOnly) {
3214 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3215 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3216 forwardPointers[type.getReferentType()],
3217 referentType);
3218 }
3219 }
3220 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003221 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224 }
3225
3226 if (type.isMatrix())
3227 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3228 else {
3229 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3230 if (type.getVectorSize() > 1)
3231 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3232 }
3233
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003234 if (type.isCoopMat()) {
3235 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3236 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3237 if (type.getBasicType() == glslang::EbtFloat16)
3238 builder.addCapability(spv::CapabilityFloat16);
3239
3240 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3241 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3242 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3243
3244 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3245 }
3246
John Kessenich140f3df2015-06-26 16:58:36 -06003247 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003248 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3249
John Kessenichc9a80832015-09-12 12:17:44 -06003250 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003251 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003252 // We need to decorate array strides for types needing explicit layout, except blocks.
3253 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003254 // Use a dummy glslang type for querying internal strides of
3255 // arrays of arrays, but using just a one-dimensional array.
3256 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003257 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3258 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003259
3260 // Will compute the higher-order strides here, rather than making a whole
3261 // pile of types and doing repetitive recursion on their contents.
3262 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3263 }
John Kessenichf8842e52016-01-04 19:22:56 -07003264
3265 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003266 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003267 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003268 if (stride > 0)
3269 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003270 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003271 }
3272 } else {
3273 // single-dimensional array, and don't yet have stride
3274
John Kessenichf8842e52016-01-04 19:22:56 -07003275 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003276 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3277 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003278 }
John Kessenich31ed4832015-09-09 17:51:38 -06003279
John Kessenichead86222018-03-28 18:01:20 -06003280 // Do the outer dimension, which might not be known for a runtime-sized array.
3281 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3282 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003283 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003284 else {
3285 if (!lastBufferBlockMember) {
3286 builder.addExtension("SPV_EXT_descriptor_indexing");
3287 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3288 }
John Kessenichead86222018-03-28 18:01:20 -06003289 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003290 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003291 if (stride > 0)
3292 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003293 }
3294
3295 return spvType;
3296}
3297
John Kessenich0e737842017-03-24 18:38:16 -06003298// TODO: this functionality should exist at a higher level, in creating the AST
3299//
3300// Identify interface members that don't have their required extension turned on.
3301//
3302bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3303{
Chao Chen3c366992018-09-19 11:41:59 -07003304#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003305 auto& extensions = glslangIntermediate->getRequestedExtensions();
3306
Rex Xubcf291a2017-03-29 23:01:36 +08003307 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3308 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3309 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003310 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3311 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3312 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003313
3314 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3315 if (member.getFieldName() == "gl_ViewportMask" &&
3316 extensions.find("GL_NV_viewport_array2") == extensions.end())
3317 return true;
3318 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3319 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3320 return true;
3321 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3322 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3323 return true;
3324 }
3325#endif
John Kessenich0e737842017-03-24 18:38:16 -06003326
3327 return false;
3328};
3329
John Kessenich6090df02016-06-30 21:18:02 -06003330// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3331// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3332// Mutually recursive with convertGlslangToSpvType().
3333spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3334 const glslang::TTypeList* glslangMembers,
3335 glslang::TLayoutPacking explicitLayout,
3336 const glslang::TQualifier& qualifier)
3337{
3338 // Create a vector of struct types for SPIR-V to consume
3339 std::vector<spv::Id> spvMembers;
3340 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 -06003341 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003342 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3343 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3344 if (glslangMember.hiddenMember()) {
3345 ++memberDelta;
3346 if (type.getBasicType() == glslang::EbtBlock)
3347 memberRemapper[glslangMembers][i] = -1;
3348 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003349 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003350 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003351 if (filterMember(glslangMember))
3352 continue;
3353 }
John Kessenich6090df02016-06-30 21:18:02 -06003354 // modify just this child's view of the qualifier
3355 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3356 InheritQualifiers(memberQualifier, qualifier);
3357
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003358 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003359 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003360 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003361
3362 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003363 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3364 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003365
3366 // Make forward pointers for any pointer members, and create a list of members to
3367 // convert to spirv types after creating the struct.
3368 if (glslangMember.getBasicType() == glslang::EbtReference) {
3369 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3370 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3371 }
3372 spvMembers.push_back(
3373 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3374 } else {
3375 spvMembers.push_back(
3376 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3377 }
John Kessenich6090df02016-06-30 21:18:02 -06003378 }
3379 }
3380
3381 // Make the SPIR-V type
3382 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003383 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003384 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3385
3386 // Decorate it
3387 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3388
John Kessenichd72f4882019-01-16 14:55:37 +07003389 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003390 auto it = deferredForwardPointers[i];
3391 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3392 }
3393
John Kessenich6090df02016-06-30 21:18:02 -06003394 return spvType;
3395}
3396
3397void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3398 const glslang::TTypeList* glslangMembers,
3399 glslang::TLayoutPacking explicitLayout,
3400 const glslang::TQualifier& qualifier,
3401 spv::Id spvType)
3402{
3403 // Name and decorate the non-hidden members
3404 int offset = -1;
3405 int locationOffset = 0; // for use within the members of this struct
3406 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3407 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3408 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003409 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003410 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003411 if (filterMember(glslangMember))
3412 continue;
3413 }
John Kessenich6090df02016-06-30 21:18:02 -06003414
3415 // modify just this child's view of the qualifier
3416 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3417 InheritQualifiers(memberQualifier, qualifier);
3418
3419 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003420 if (member < 0)
3421 continue;
3422
3423 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3424 builder.addMemberDecoration(spvType, member,
3425 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3426 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3427 // Add interpolation and auxiliary storage decorations only to
3428 // top-level members of Input and Output storage classes
3429 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3430 type.getQualifier().storage == glslang::EvqVaryingOut) {
3431 if (type.getBasicType() == glslang::EbtBlock ||
3432 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3433 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3434 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003435#ifdef NV_EXTENSIONS
3436 addMeshNVDecoration(spvType, member, memberQualifier);
3437#endif
John Kessenich6090df02016-06-30 21:18:02 -06003438 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003439 }
3440 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003441
John Kessenich5d610ee2018-03-07 18:05:55 -07003442 if (type.getBasicType() == glslang::EbtBlock &&
3443 qualifier.storage == glslang::EvqBuffer) {
3444 // Add memory decorations only to top-level members of shader storage block
3445 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003446 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003447 for (unsigned int i = 0; i < memory.size(); ++i)
3448 builder.addMemberDecoration(spvType, member, memory[i]);
3449 }
John Kessenich6090df02016-06-30 21:18:02 -06003450
John Kessenich5d610ee2018-03-07 18:05:55 -07003451 // Location assignment was already completed correctly by the front end,
3452 // just track whether a member needs to be decorated.
3453 // Ignore member locations if the container is an array, as that's
3454 // ill-specified and decisions have been made to not allow this.
3455 if (! type.isArray() && memberQualifier.hasLocation())
3456 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003457
John Kessenich5d610ee2018-03-07 18:05:55 -07003458 if (qualifier.hasLocation()) // track for upcoming inheritance
3459 locationOffset += glslangIntermediate->computeTypeLocationSize(
3460 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003461
John Kessenich5d610ee2018-03-07 18:05:55 -07003462 // component, XFB, others
3463 if (glslangMember.getQualifier().hasComponent())
3464 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3465 glslangMember.getQualifier().layoutComponent);
3466 if (glslangMember.getQualifier().hasXfbOffset())
3467 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3468 glslangMember.getQualifier().layoutXfbOffset);
3469 else if (explicitLayout != glslang::ElpNone) {
3470 // figure out what to do with offset, which is accumulating
3471 int nextOffset;
3472 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3473 if (offset >= 0)
3474 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3475 offset = nextOffset;
3476 }
John Kessenich6090df02016-06-30 21:18:02 -06003477
John Kessenich5d610ee2018-03-07 18:05:55 -07003478 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3479 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3480 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003481
John Kessenich5d610ee2018-03-07 18:05:55 -07003482 // built-in variable decorations
3483 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3484 if (builtIn != spv::BuiltInMax)
3485 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003486
John Kessenich5611c6d2018-04-05 11:25:02 -06003487 // nonuniform
3488 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3489
John Kessenichead86222018-03-28 18:01:20 -06003490 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3491 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3492 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3493 memberQualifier.semanticName);
3494 }
3495
chaoc771d89f2017-01-13 01:10:53 -08003496#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003497 if (builtIn == spv::BuiltInLayer) {
3498 // SPV_NV_viewport_array2 extension
3499 if (glslangMember.getQualifier().layoutViewportRelative){
3500 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3501 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3502 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003503 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003504 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3505 builder.addMemberDecoration(spvType, member,
3506 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3507 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3508 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3509 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003510 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003511 }
3512 if (glslangMember.getQualifier().layoutPassthrough) {
3513 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3514 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3515 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3516 }
chaoc771d89f2017-01-13 01:10:53 -08003517#endif
John Kessenich6090df02016-06-30 21:18:02 -06003518 }
3519
3520 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003521 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3522 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003523}
3524
John Kessenich6c292d32016-02-15 20:58:50 -07003525// Turn the expression forming the array size into an id.
3526// This is not quite trivial, because of specialization constants.
3527// Sometimes, a raw constant is turned into an Id, and sometimes
3528// a specialization constant expression is.
3529spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3530{
3531 // First, see if this is sized with a node, meaning a specialization constant:
3532 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3533 if (specNode != nullptr) {
3534 builder.clearAccessChain();
3535 specNode->traverse(this);
3536 return accessChainLoad(specNode->getAsTyped()->getType());
3537 }
qining25262b32016-05-06 17:25:16 -04003538
John Kessenich6c292d32016-02-15 20:58:50 -07003539 // Otherwise, need a compile-time (front end) size, get it:
3540 int size = arraySizes.getDimSize(dim);
3541 assert(size > 0);
3542 return builder.makeUintConstant(size);
3543}
3544
John Kessenich103bef92016-02-08 21:38:15 -07003545// Wrap the builder's accessChainLoad to:
3546// - localize handling of RelaxedPrecision
3547// - use the SPIR-V inferred type instead of another conversion of the glslang type
3548// (avoids unnecessary work and possible type punning for structures)
3549// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003550spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3551{
John Kessenich103bef92016-02-08 21:38:15 -07003552 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003553
3554 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3555 coherentFlags |= TranslateCoherent(type);
3556
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003557 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003558 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003559
John Kessenich5611c6d2018-04-05 11:25:02 -06003560 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003561 TranslateNonUniformDecoration(type.getQualifier()),
3562 nominalTypeId,
3563 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003564 TranslateMemoryScope(coherentFlags),
3565 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003566
3567 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003568 if (type.getBasicType() == glslang::EbtBool) {
3569 if (builder.isScalarType(nominalTypeId)) {
3570 // Conversion for bool
3571 spv::Id boolType = builder.makeBoolType();
3572 if (nominalTypeId != boolType)
3573 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3574 } else if (builder.isVectorType(nominalTypeId)) {
3575 // Conversion for bvec
3576 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3577 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3578 if (nominalTypeId != bvecType)
3579 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3580 }
3581 }
John Kessenich103bef92016-02-08 21:38:15 -07003582
3583 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003584}
3585
Rex Xu27253232016-02-23 17:51:09 +08003586// Wrap the builder's accessChainStore to:
3587// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003588//
3589// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003590void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3591{
3592 // Need to convert to abstract types when necessary
3593 if (type.getBasicType() == glslang::EbtBool) {
3594 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3595
3596 if (builder.isScalarType(nominalTypeId)) {
3597 // Conversion for bool
3598 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003599 if (nominalTypeId != boolType) {
3600 // keep these outside arguments, for determinant order-of-evaluation
3601 spv::Id one = builder.makeUintConstant(1);
3602 spv::Id zero = builder.makeUintConstant(0);
3603 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3604 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003605 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003606 } else if (builder.isVectorType(nominalTypeId)) {
3607 // Conversion for bvec
3608 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3609 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003610 if (nominalTypeId != bvecType) {
3611 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003612 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3613 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3614 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003615 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003616 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3617 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003618 }
3619 }
3620
Jeff Bolz36831c92018-09-05 10:11:41 -05003621 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3622 coherentFlags |= TranslateCoherent(type);
3623
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003625 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003626
Jeff Bolz36831c92018-09-05 10:11:41 -05003627 builder.accessChainStore(rvalue,
3628 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003629 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003630}
3631
John Kessenich4bf71552016-09-02 11:20:21 -06003632// For storing when types match at the glslang level, but not might match at the
3633// SPIR-V level.
3634//
3635// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003636// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003637// as in a member-decorated way.
3638//
3639// NOTE: This function can handle any store request; if it's not special it
3640// simplifies to a simple OpStore.
3641//
3642// Implicitly uses the existing builder.accessChain as the storage target.
3643void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3644{
John Kessenichb3e24e42016-09-11 12:33:43 -06003645 // we only do the complex path here if it's an aggregate
3646 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003647 accessChainStore(type, rValue);
3648 return;
3649 }
3650
John Kessenichb3e24e42016-09-11 12:33:43 -06003651 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003652 spv::Id rType = builder.getTypeId(rValue);
3653 spv::Id lValue = builder.accessChainGetLValue();
3654 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3655 if (lType == rType) {
3656 accessChainStore(type, rValue);
3657 return;
3658 }
3659
John Kessenichb3e24e42016-09-11 12:33:43 -06003660 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003661 // where the two types were the same type in GLSL. This requires member
3662 // by member copy, recursively.
3663
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003664 // SPIR-V 1.4 added an instruction to do help do this.
3665 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3666 // However, bool in uniform space is changed to int, so
3667 // OpCopyLogical does not work for that.
3668 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3669 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3670 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3671 if (lBool == rBool) {
3672 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3673 accessChainStore(type, logicalCopy);
3674 return;
3675 }
3676 }
3677
John Kessenichb3e24e42016-09-11 12:33:43 -06003678 // If an array, copy element by element.
3679 if (type.isArray()) {
3680 glslang::TType glslangElementType(type, 0);
3681 spv::Id elementRType = builder.getContainedTypeId(rType);
3682 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3683 // get the source member
3684 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003685
John Kessenichb3e24e42016-09-11 12:33:43 -06003686 // set up the target storage
3687 builder.clearAccessChain();
3688 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003689 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003690
John Kessenichb3e24e42016-09-11 12:33:43 -06003691 // store the member
3692 multiTypeStore(glslangElementType, elementRValue);
3693 }
3694 } else {
3695 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003696
John Kessenichb3e24e42016-09-11 12:33:43 -06003697 // loop over structure members
3698 const glslang::TTypeList& members = *type.getStruct();
3699 for (int m = 0; m < (int)members.size(); ++m) {
3700 const glslang::TType& glslangMemberType = *members[m].type;
3701
3702 // get the source member
3703 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3704 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3705
3706 // set up the target storage
3707 builder.clearAccessChain();
3708 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003709 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003710
3711 // store the member
3712 multiTypeStore(glslangMemberType, memberRValue);
3713 }
John Kessenich4bf71552016-09-02 11:20:21 -06003714 }
3715}
3716
John Kessenichf85e8062015-12-19 13:57:10 -07003717// Decide whether or not this type should be
3718// decorated with offsets and strides, and if so
3719// whether std140 or std430 rules should be applied.
3720glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003721{
John Kessenichf85e8062015-12-19 13:57:10 -07003722 // has to be a block
3723 if (type.getBasicType() != glslang::EbtBlock)
3724 return glslang::ElpNone;
3725
Chao Chen3c366992018-09-19 11:41:59 -07003726 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003727 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003728 type.getQualifier().storage != glslang::EvqBuffer &&
3729 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003730 return glslang::ElpNone;
3731
3732 // return the layout to use
3733 switch (type.getQualifier().layoutPacking) {
3734 case glslang::ElpStd140:
3735 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003736 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003737 return type.getQualifier().layoutPacking;
3738 default:
3739 return glslang::ElpNone;
3740 }
John Kessenich31ed4832015-09-09 17:51:38 -06003741}
3742
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003743// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003744int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003745{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003746 int size;
John Kessenich49987892015-12-29 17:11:44 -07003747 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003748 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003749
3750 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003751}
3752
John Kessenich49987892015-12-29 17:11:44 -07003753// 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 -07003754// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003755int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003756{
John Kessenich49987892015-12-29 17:11:44 -07003757 glslang::TType elementType;
3758 elementType.shallowCopy(matrixType);
3759 elementType.clearArraySizes();
3760
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003761 int size;
John Kessenich49987892015-12-29 17:11:44 -07003762 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003763 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003764
3765 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003766}
3767
John Kessenich5e4b1242015-08-06 22:53:06 -06003768// Given a member type of a struct, realign the current offset for it, and compute
3769// the next (not yet aligned) offset for the next member, which will get aligned
3770// on the next call.
3771// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3772// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3773// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003774void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003775 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003776{
3777 // this will get a positive value when deemed necessary
3778 nextOffset = -1;
3779
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 // override anything in currentOffset with user-set offset
3781 if (memberType.getQualifier().hasOffset())
3782 currentOffset = memberType.getQualifier().layoutOffset;
3783
3784 // It could be that current linker usage in glslang updated all the layoutOffset,
3785 // in which case the following code does not matter. But, that's not quite right
3786 // once cross-compilation unit GLSL validation is done, as the original user
3787 // settings are needed in layoutOffset, and then the following will come into play.
3788
John Kessenichf85e8062015-12-19 13:57:10 -07003789 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003790 if (! memberType.getQualifier().hasOffset())
3791 currentOffset = -1;
3792
3793 return;
3794 }
3795
John Kessenichf85e8062015-12-19 13:57:10 -07003796 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 if (currentOffset < 0)
3798 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003799
John Kessenich5e4b1242015-08-06 22:53:06 -06003800 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3801 // but possibly not yet correctly aligned.
3802
3803 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003804 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003805 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003806
3807 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003808 // TODO: make this consistent in early phases of code:
3809 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3810 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3811 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003812 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003813 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003814 int dummySize;
3815 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3816 if (componentAlignment <= 4)
3817 memberAlignment = componentAlignment;
3818 }
3819
3820 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003822
3823 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003824 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003825 glslang::RoundToPow2(currentOffset, 16);
3826
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 nextOffset = currentOffset + memberSize;
3828}
3829
David Netoa901ffe2016-06-08 14:11:40 +01003830void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003831{
David Netoa901ffe2016-06-08 14:11:40 +01003832 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3833 switch (glslangBuiltIn)
3834 {
3835 case glslang::EbvClipDistance:
3836 case glslang::EbvCullDistance:
3837 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003838#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003839 case glslang::EbvViewportMaskNV:
3840 case glslang::EbvSecondaryPositionNV:
3841 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003842 case glslang::EbvPositionPerViewNV:
3843 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003844 case glslang::EbvTaskCountNV:
3845 case glslang::EbvPrimitiveCountNV:
3846 case glslang::EbvPrimitiveIndicesNV:
3847 case glslang::EbvClipDistancePerViewNV:
3848 case glslang::EbvCullDistancePerViewNV:
3849 case glslang::EbvLayerPerViewNV:
3850 case glslang::EbvMeshViewCountNV:
3851 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003852#endif
David Netoa901ffe2016-06-08 14:11:40 +01003853 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3854 // Alternately, we could just call this for any glslang built-in, since the
3855 // capability already guards against duplicates.
3856 TranslateBuiltInDecoration(glslangBuiltIn, false);
3857 break;
3858 default:
3859 // Capabilities were already generated when the struct was declared.
3860 break;
3861 }
John Kessenichebb50532016-05-16 19:22:05 -06003862}
3863
John Kessenich6fccb3c2016-09-19 16:01:41 -06003864bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003865{
John Kessenicheee9d532016-09-19 18:09:30 -06003866 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003867}
3868
John Kessenichd41993d2017-09-10 15:21:05 -06003869// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003870// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3871// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003872bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003873{
John Kessenich6a14f782017-12-04 02:48:10 -07003874 assert(qualifier == glslang::EvqIn ||
3875 qualifier == glslang::EvqOut ||
3876 qualifier == glslang::EvqInOut ||
3877 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003878 return qualifier != glslang::EvqConstReadOnly;
3879}
3880
3881// Is parameter pass-by-original?
3882bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3883 bool implicitThisParam)
3884{
3885 if (implicitThisParam) // implicit this
3886 return true;
3887 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003888 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003889 return paramType.containsOpaque() || // sampler, etc.
3890 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3891}
3892
John Kessenich140f3df2015-06-26 16:58:36 -06003893// Make all the functions, skeletally, without actually visiting their bodies.
3894void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3895{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003896 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003897 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3898 if (paramPrecision != spv::NoPrecision)
3899 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003900 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003901 if (type.getBasicType() == glslang::EbtReference) {
3902 // Original and non-writable params pass the pointer directly and
3903 // use restrict/aliased, others are stored to a pointer in Function
3904 // memory and use RestrictPointer/AliasedPointer.
3905 if (originalParam(type.getQualifier().storage, type, false) ||
3906 !writableParam(type.getQualifier().storage)) {
3907 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3908 } else {
3909 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3910 }
3911 }
John Kessenichfad62972017-07-18 02:35:46 -06003912 };
3913
John Kessenich140f3df2015-06-26 16:58:36 -06003914 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3915 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003916 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003917 continue;
3918
3919 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003920 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003921 //
qining25262b32016-05-06 17:25:16 -04003922 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003923 // function. What it is an address of varies:
3924 //
John Kessenich4bf71552016-09-02 11:20:21 -06003925 // - "in" parameters not marked as "const" can be written to without modifying the calling
3926 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003927 //
3928 // - "const in" parameters can just be the r-value, as no writes need occur.
3929 //
John Kessenich4bf71552016-09-02 11:20:21 -06003930 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3931 // 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 -06003932
3933 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003934 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003935 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3936
John Kessenichfad62972017-07-18 02:35:46 -06003937 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3938 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003939
John Kessenichfad62972017-07-18 02:35:46 -06003940 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003941 for (int p = 0; p < (int)parameters.size(); ++p) {
3942 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3943 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003944 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003945 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003946 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003947 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3948 else
John Kessenich4bf71552016-09-02 11:20:21 -06003949 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003950 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003951 paramTypes.push_back(typeId);
3952 }
3953
3954 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003955 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3956 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003957 glslFunction->getName().c_str(), paramTypes,
3958 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003959 if (implicitThis)
3960 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003961
3962 // Track function to emit/call later
3963 functionMap[glslFunction->getName().c_str()] = function;
3964
3965 // Set the parameter id's
3966 for (int p = 0; p < (int)parameters.size(); ++p) {
3967 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3968 // give a name too
3969 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3970 }
3971 }
3972}
3973
3974// Process all the initializers, while skipping the functions and link objects
3975void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3976{
3977 builder.setBuildPoint(shaderEntry->getLastBlock());
3978 for (int i = 0; i < (int)initializers.size(); ++i) {
3979 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3980 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3981
3982 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003983 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003984 initializer->traverse(this);
3985 }
3986 }
3987}
3988
3989// Process all the functions, while skipping initializers.
3990void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3991{
3992 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3993 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003994 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003995 node->traverse(this);
3996 }
3997}
3998
3999void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4000{
qining25262b32016-05-06 17:25:16 -04004001 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004002 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004003 currentFunction = functionMap[node->getName().c_str()];
4004 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004005 builder.setBuildPoint(functionBlock);
4006}
4007
Rex Xu04db3f52015-09-16 11:44:02 +08004008void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004009{
Rex Xufc618912015-09-09 16:42:49 +08004010 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004011
4012 glslang::TSampler sampler = {};
4013 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004014#ifdef AMD_EXTENSIONS
4015 bool f16ShadowCompare = false;
4016#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004017 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004018 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4019 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004020#ifdef AMD_EXTENSIONS
4021 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4022#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004023 }
4024
John Kessenich140f3df2015-06-26 16:58:36 -06004025 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4026 builder.clearAccessChain();
4027 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004028
4029 // Special case l-value operands
4030 bool lvalue = false;
4031 switch (node.getOp()) {
4032 case glslang::EOpImageAtomicAdd:
4033 case glslang::EOpImageAtomicMin:
4034 case glslang::EOpImageAtomicMax:
4035 case glslang::EOpImageAtomicAnd:
4036 case glslang::EOpImageAtomicOr:
4037 case glslang::EOpImageAtomicXor:
4038 case glslang::EOpImageAtomicExchange:
4039 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004040 case glslang::EOpImageAtomicLoad:
4041 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004042 if (i == 0)
4043 lvalue = true;
4044 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004045 case glslang::EOpSparseImageLoad:
4046 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4047 lvalue = true;
4048 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004049#ifdef AMD_EXTENSIONS
4050 case glslang::EOpSparseTexture:
4051 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4052 lvalue = true;
4053 break;
4054 case glslang::EOpSparseTextureClamp:
4055 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4056 lvalue = true;
4057 break;
4058 case glslang::EOpSparseTextureLod:
4059 case glslang::EOpSparseTextureOffset:
4060 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4061 lvalue = true;
4062 break;
4063#else
Rex Xu48edadf2015-12-31 16:11:41 +08004064 case glslang::EOpSparseTexture:
4065 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4066 lvalue = true;
4067 break;
4068 case glslang::EOpSparseTextureClamp:
4069 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4070 lvalue = true;
4071 break;
4072 case glslang::EOpSparseTextureLod:
4073 case glslang::EOpSparseTextureOffset:
4074 if (i == 3)
4075 lvalue = true;
4076 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004077#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004078 case glslang::EOpSparseTextureFetch:
4079 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4080 lvalue = true;
4081 break;
4082 case glslang::EOpSparseTextureFetchOffset:
4083 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4084 lvalue = true;
4085 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004086#ifdef AMD_EXTENSIONS
4087 case glslang::EOpSparseTextureLodOffset:
4088 case glslang::EOpSparseTextureGrad:
4089 case glslang::EOpSparseTextureOffsetClamp:
4090 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4091 lvalue = true;
4092 break;
4093 case glslang::EOpSparseTextureGradOffset:
4094 case glslang::EOpSparseTextureGradClamp:
4095 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4096 lvalue = true;
4097 break;
4098 case glslang::EOpSparseTextureGradOffsetClamp:
4099 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4100 lvalue = true;
4101 break;
4102#else
Rex Xu48edadf2015-12-31 16:11:41 +08004103 case glslang::EOpSparseTextureLodOffset:
4104 case glslang::EOpSparseTextureGrad:
4105 case glslang::EOpSparseTextureOffsetClamp:
4106 if (i == 4)
4107 lvalue = true;
4108 break;
4109 case glslang::EOpSparseTextureGradOffset:
4110 case glslang::EOpSparseTextureGradClamp:
4111 if (i == 5)
4112 lvalue = true;
4113 break;
4114 case glslang::EOpSparseTextureGradOffsetClamp:
4115 if (i == 6)
4116 lvalue = true;
4117 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004118#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004119 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004120 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4121 lvalue = true;
4122 break;
4123 case glslang::EOpSparseTextureGatherOffset:
4124 case glslang::EOpSparseTextureGatherOffsets:
4125 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4126 lvalue = true;
4127 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004128#ifdef AMD_EXTENSIONS
4129 case glslang::EOpSparseTextureGatherLod:
4130 if (i == 3)
4131 lvalue = true;
4132 break;
4133 case glslang::EOpSparseTextureGatherLodOffset:
4134 case glslang::EOpSparseTextureGatherLodOffsets:
4135 if (i == 4)
4136 lvalue = true;
4137 break;
Rex Xu129799a2017-07-05 17:23:28 +08004138 case glslang::EOpSparseImageLoadLod:
4139 if (i == 3)
4140 lvalue = true;
4141 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004142#endif
Chao Chen3a137962018-09-19 11:41:27 -07004143#ifdef NV_EXTENSIONS
4144 case glslang::EOpImageSampleFootprintNV:
4145 if (i == 4)
4146 lvalue = true;
4147 break;
4148 case glslang::EOpImageSampleFootprintClampNV:
4149 case glslang::EOpImageSampleFootprintLodNV:
4150 if (i == 5)
4151 lvalue = true;
4152 break;
4153 case glslang::EOpImageSampleFootprintGradNV:
4154 if (i == 6)
4155 lvalue = true;
4156 break;
4157 case glslang::EOpImageSampleFootprintGradClampNV:
4158 if (i == 7)
4159 lvalue = true;
4160 break;
4161#endif
Rex Xufc618912015-09-09 16:42:49 +08004162 default:
4163 break;
4164 }
4165
Rex Xu6b86d492015-09-16 17:48:22 +08004166 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004167 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004168 else
John Kessenich32cfd492016-02-02 12:37:46 -07004169 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004170 }
4171}
4172
John Kessenichfc51d282015-08-19 13:34:18 -06004173void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004174{
John Kessenichfc51d282015-08-19 13:34:18 -06004175 builder.clearAccessChain();
4176 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004177 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004178}
John Kessenich140f3df2015-06-26 16:58:36 -06004179
John Kessenichfc51d282015-08-19 13:34:18 -06004180spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4181{
John Kesseniche485c7a2017-05-31 18:50:53 -06004182 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004183 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004184
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004185 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004186
John Kessenichfc51d282015-08-19 13:34:18 -06004187 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004188
John Kessenichf43c7392019-03-31 10:51:57 -06004189 const glslang::TType &imageType = node->getAsAggregate()
4190 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4191 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004192 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004193#ifdef AMD_EXTENSIONS
4194 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004195 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4196 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004197#endif
4198
John Kessenichf43c7392019-03-31 10:51:57 -06004199 const auto signExtensionMask = [&]() {
4200 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4201 if (sampler.type == glslang::EbtUint)
4202 return spv::ImageOperandsZeroExtendMask;
4203 else if (sampler.type == glslang::EbtInt)
4204 return spv::ImageOperandsSignExtendMask;
4205 }
4206 return spv::ImageOperandsMaskNone;
4207 };
4208
John Kessenichfc51d282015-08-19 13:34:18 -06004209 std::vector<spv::Id> arguments;
4210 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004211 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004212 else
4213 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004214 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004215
4216 spv::Builder::TextureParameters params = { };
4217 params.sampler = arguments[0];
4218
Rex Xu04db3f52015-09-16 11:44:02 +08004219 glslang::TCrackedTextureOp cracked;
4220 node->crackTexture(sampler, cracked);
4221
amhagan05506bb2017-06-13 16:53:02 -04004222 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004223
John Kessenichfc51d282015-08-19 13:34:18 -06004224 // Check for queries
4225 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004226 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4227 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004228 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004229
John Kessenichfc51d282015-08-19 13:34:18 -06004230 switch (node->getOp()) {
4231 case glslang::EOpImageQuerySize:
4232 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004233 if (arguments.size() > 1) {
4234 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004235 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004236 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004237 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004238 case glslang::EOpImageQuerySamples:
4239 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004240 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004241 case glslang::EOpTextureQueryLod:
4242 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004243 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004244 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004245 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004246 case glslang::EOpSparseTexelsResident:
4247 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004248 default:
4249 assert(0);
4250 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004251 }
John Kessenich140f3df2015-06-26 16:58:36 -06004252 }
4253
LoopDawg4425f242018-02-18 11:40:01 -07004254 int components = node->getType().getVectorSize();
4255
4256 if (node->getOp() == glslang::EOpTextureFetch) {
4257 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4258 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4259 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4260 // here around e.g. which ones return scalars or other types.
4261 components = 4;
4262 }
4263
4264 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4265
4266 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4267
Rex Xufc618912015-09-09 16:42:49 +08004268 // Check for image functions other than queries
4269 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004270 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004271 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004272 spv::IdImmediate image = { true, *(opIt++) };
4273 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004274
4275 // Handle subpass operations
4276 // TODO: GLSL should change to have the "MS" only on the type rather than the
4277 // built-in function.
4278 if (cracked.subpass) {
4279 // add on the (0,0) coordinate
4280 spv::Id zero = builder.makeIntConstant(0);
4281 std::vector<spv::Id> comps;
4282 comps.push_back(zero);
4283 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004284 spv::IdImmediate coord = { true,
4285 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4286 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004287 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4288 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004289 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004290 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4291 }
4292 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004293 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004294 if (sampler.ms) {
4295 spv::IdImmediate imageOperand = { true, *(opIt++) };
4296 operands.push_back(imageOperand);
4297 }
John Kessenich6c292d32016-02-15 20:58:50 -07004298 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004299 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4300 builder.setPrecision(result, precision);
4301 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004302 }
4303
John Kessenich149afc32018-08-14 13:31:43 -06004304 spv::IdImmediate coord = { true, *(opIt++) };
4305 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004306#ifdef AMD_EXTENSIONS
4307 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4308#else
John Kessenich56bab042015-09-16 10:54:31 -06004309 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004310#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004311 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004312 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004313 mask = mask | spv::ImageOperandsSampleMask;
4314 }
Rex Xu129799a2017-07-05 17:23:28 +08004315#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004316 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004317 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4318 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004319 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004320 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004321#endif
4322 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4323 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004324 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004325 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004326 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4327 operands.push_back(imageOperands);
4328 }
4329 if (mask & spv::ImageOperandsSampleMask) {
4330 spv::IdImmediate imageOperand = { true, *opIt++ };
4331 operands.push_back(imageOperand);
4332 }
4333#ifdef AMD_EXTENSIONS
4334 if (mask & spv::ImageOperandsLodMask) {
4335 spv::IdImmediate imageOperand = { true, *opIt++ };
4336 operands.push_back(imageOperand);
4337 }
4338#endif
4339 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004340 spv::IdImmediate imageOperand = { true,
4341 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004342 operands.push_back(imageOperand);
4343 }
4344
John Kessenich149afc32018-08-14 13:31:43 -06004345 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004346 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004347
John Kessenich149afc32018-08-14 13:31:43 -06004348 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004349 builder.setPrecision(result[0], precision);
4350
4351 // If needed, add a conversion constructor to the proper size.
4352 if (components != node->getType().getVectorSize())
4353 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4354
4355 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004356#ifdef AMD_EXTENSIONS
4357 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4358#else
John Kessenich56bab042015-09-16 10:54:31 -06004359 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004360#endif
Rex Xu129799a2017-07-05 17:23:28 +08004361
Jeff Bolz36831c92018-09-05 10:11:41 -05004362 // Push the texel value before the operands
4363#ifdef AMD_EXTENSIONS
4364 if (sampler.ms || cracked.lod) {
4365#else
4366 if (sampler.ms) {
4367#endif
John Kessenich149afc32018-08-14 13:31:43 -06004368 spv::IdImmediate texel = { true, *(opIt + 1) };
4369 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004370 } else {
4371 spv::IdImmediate texel = { true, *opIt };
4372 operands.push_back(texel);
4373 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004374
4375 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4376 if (sampler.ms) {
4377 mask = mask | spv::ImageOperandsSampleMask;
4378 }
4379#ifdef AMD_EXTENSIONS
4380 if (cracked.lod) {
4381 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4382 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4383 mask = mask | spv::ImageOperandsLodMask;
4384 }
4385#endif
4386 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4387 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004388 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004389 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004390 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4391 operands.push_back(imageOperands);
4392 }
4393 if (mask & spv::ImageOperandsSampleMask) {
4394 spv::IdImmediate imageOperand = { true, *opIt++ };
4395 operands.push_back(imageOperand);
4396 }
4397#ifdef AMD_EXTENSIONS
4398 if (mask & spv::ImageOperandsLodMask) {
4399 spv::IdImmediate imageOperand = { true, *opIt++ };
4400 operands.push_back(imageOperand);
4401 }
4402#endif
4403 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004404 spv::IdImmediate imageOperand = { true,
4405 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004406 operands.push_back(imageOperand);
4407 }
4408
John Kessenich56bab042015-09-16 10:54:31 -06004409 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004410 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004411 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004412 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004413#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004414 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4415 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004416#else
Rex Xu5eafa472016-02-19 22:24:03 +08004417 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004418#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004419 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004420 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004421 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4422
Jeff Bolz36831c92018-09-05 10:11:41 -05004423 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004424 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004425 mask = mask | spv::ImageOperandsSampleMask;
4426 }
Rex Xu129799a2017-07-05 17:23:28 +08004427#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004428 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004429 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4430 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4431
Jeff Bolz36831c92018-09-05 10:11:41 -05004432 mask = mask | spv::ImageOperandsLodMask;
4433 }
4434#endif
4435 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4436 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004437 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004438 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004439 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004440 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004441 }
4442 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004443 spv::IdImmediate imageOperand = { true, *opIt++ };
4444 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004445 }
4446#ifdef AMD_EXTENSIONS
4447 if (mask & spv::ImageOperandsLodMask) {
4448 spv::IdImmediate imageOperand = { true, *opIt++ };
4449 operands.push_back(imageOperand);
4450 }
Rex Xu129799a2017-07-05 17:23:28 +08004451#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004452 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4453 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4454 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004455 }
4456
4457 // Create the return type that was a special structure
4458 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004459 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004460 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4461 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4462
4463 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4464
4465 // Decode the return type
4466 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4467 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004468 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004469 // Process image atomic operations
4470
4471 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4472 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004473 // For non-MS, the sample value should be 0
4474 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4475 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004476
Jeff Bolz36831c92018-09-05 10:11:41 -05004477 spv::Id resultTypeId;
4478 // imageAtomicStore has a void return type so base the pointer type on
4479 // the type of the value operand.
4480 if (node->getOp() == glslang::EOpImageAtomicStore) {
4481 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4482 } else {
4483 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4484 }
John Kessenich56bab042015-09-16 10:54:31 -06004485 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004486
4487 std::vector<spv::Id> operands;
4488 operands.push_back(pointer);
4489 for (; opIt != arguments.end(); ++opIt)
4490 operands.push_back(*opIt);
4491
John Kessenich8c8505c2016-07-26 12:50:38 -06004492 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004493 }
4494 }
4495
amhagan05506bb2017-06-13 16:53:02 -04004496#ifdef AMD_EXTENSIONS
4497 // Check for fragment mask functions other than queries
4498 if (cracked.fragMask) {
4499 assert(sampler.ms);
4500
4501 auto opIt = arguments.begin();
4502 std::vector<spv::Id> operands;
4503
4504 // Extract the image if necessary
4505 if (builder.isSampledImage(params.sampler))
4506 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4507
4508 operands.push_back(params.sampler);
4509 ++opIt;
4510
4511 if (sampler.isSubpass()) {
4512 // add on the (0,0) coordinate
4513 spv::Id zero = builder.makeIntConstant(0);
4514 std::vector<spv::Id> comps;
4515 comps.push_back(zero);
4516 comps.push_back(zero);
4517 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4518 }
4519
4520 for (; opIt != arguments.end(); ++opIt)
4521 operands.push_back(*opIt);
4522
4523 spv::Op fragMaskOp = spv::OpNop;
4524 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4525 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4526 else if (node->getOp() == glslang::EOpFragmentFetch)
4527 fragMaskOp = spv::OpFragmentFetchAMD;
4528
4529 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4530 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4531 return builder.createOp(fragMaskOp, resultType(), operands);
4532 }
4533#endif
4534
Rex Xufc618912015-09-09 16:42:49 +08004535 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004536 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004537#ifdef NV_EXTENSIONS
4538 bool imageFootprint = node->isImageFootprint();
4539#endif
4540
Rex Xu71519fe2015-11-11 15:35:47 +08004541 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4542
John Kessenichfc51d282015-08-19 13:34:18 -06004543 // check for bias argument
4544 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004545#ifdef AMD_EXTENSIONS
4546 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4547#else
Rex Xu71519fe2015-11-11 15:35:47 +08004548 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004549#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004550 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004551#ifdef AMD_EXTENSIONS
4552 if (cracked.gather)
4553 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004554
4555 if (f16ShadowCompare)
4556 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004557#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004558 if (cracked.offset)
4559 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004560#ifdef AMD_EXTENSIONS
4561 else if (cracked.offsets)
4562 ++nonBiasArgCount;
4563#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004564 if (cracked.grad)
4565 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004566 if (cracked.lodClamp)
4567 ++nonBiasArgCount;
4568 if (sparse)
4569 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004570#ifdef NV_EXTENSIONS
4571 if (imageFootprint)
4572 //Following three extra arguments
4573 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4574 nonBiasArgCount += 3;
4575#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004576 if ((int)arguments.size() > nonBiasArgCount)
4577 bias = true;
4578 }
4579
John Kessenicha5c33d62016-06-02 23:45:21 -06004580 // See if the sampler param should really be just the SPV image part
4581 if (cracked.fetch) {
4582 // a fetch needs to have the image extracted first
4583 if (builder.isSampledImage(params.sampler))
4584 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4585 }
4586
Rex Xu225e0fc2016-11-17 17:47:59 +08004587#ifdef AMD_EXTENSIONS
4588 if (cracked.gather) {
4589 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4590 if (bias || cracked.lod ||
4591 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4592 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004593 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004594 }
4595 }
4596#endif
4597
John Kessenichfc51d282015-08-19 13:34:18 -06004598 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004599
John Kessenichfc51d282015-08-19 13:34:18 -06004600 params.coords = arguments[1];
4601 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004602 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004603
4604 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004605#ifdef AMD_EXTENSIONS
4606 if (cubeCompare || f16ShadowCompare) {
4607#else
Rex Xu48edadf2015-12-31 16:11:41 +08004608 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004609#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004610 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004611 ++extraArgs;
4612 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004613 params.Dref = arguments[2];
4614 ++extraArgs;
4615 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004616 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004617 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004618 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004619 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004620 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004621 dRefComp = builder.getNumComponents(params.coords) - 1;
4622 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004623 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4624 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004625
4626 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004627 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004628 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004629 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004630 } else if (glslangIntermediate->getStage() != EShLangFragment
4631#ifdef NV_EXTENSIONS
4632 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4633 && !(glslangIntermediate->getStage() == EShLangCompute &&
4634 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4635#endif
4636 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004637 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4638 noImplicitLod = true;
4639 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004640
4641 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004642 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004643 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004644 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004645 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004646
4647 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004648 if (cracked.grad) {
4649 params.gradX = arguments[2 + extraArgs];
4650 params.gradY = arguments[3 + extraArgs];
4651 extraArgs += 2;
4652 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004653
4654 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004655 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004656 params.offset = arguments[2 + extraArgs];
4657 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004658 } else if (cracked.offsets) {
4659 params.offsets = arguments[2 + extraArgs];
4660 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004661 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004662
4663 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004664 if (cracked.lodClamp) {
4665 params.lodClamp = arguments[2 + extraArgs];
4666 ++extraArgs;
4667 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004668 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004669 if (sparse) {
4670 params.texelOut = arguments[2 + extraArgs];
4671 ++extraArgs;
4672 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004673
John Kessenich76d4dfc2016-06-16 12:43:23 -06004674 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004675 if (cracked.gather && ! sampler.shadow) {
4676 // default component is 0, if missing, otherwise an argument
4677 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004678 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004679 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004680 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004681 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004682 }
Chao Chen3a137962018-09-19 11:41:27 -07004683#ifdef NV_EXTENSIONS
4684 spv::Id resultStruct = spv::NoResult;
4685 if (imageFootprint) {
4686 //Following three extra arguments
4687 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4688 params.granularity = arguments[2 + extraArgs];
4689 params.coarse = arguments[3 + extraArgs];
4690 resultStruct = arguments[4 + extraArgs];
4691 extraArgs += 3;
4692 }
4693#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004694 // bias
4695 if (bias) {
4696 params.bias = arguments[2 + extraArgs];
4697 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004698 }
John Kessenichfc51d282015-08-19 13:34:18 -06004699
Chao Chen3a137962018-09-19 11:41:27 -07004700#ifdef NV_EXTENSIONS
4701 if (imageFootprint) {
4702 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4703 builder.addCapability(spv::CapabilityImageFootprintNV);
4704
4705
4706 //resultStructType(OpenGL type) contains 5 elements:
4707 //struct gl_TextureFootprint2DNV {
4708 // uvec2 anchor;
4709 // uvec2 offset;
4710 // uvec2 mask;
4711 // uint lod;
4712 // uint granularity;
4713 //};
4714 //or
4715 //struct gl_TextureFootprint3DNV {
4716 // uvec3 anchor;
4717 // uvec3 offset;
4718 // uvec2 mask;
4719 // uint lod;
4720 // uint granularity;
4721 //};
4722 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4723 assert(builder.isStructType(resultStructType));
4724
4725 //resType (SPIR-V type) contains 6 elements:
4726 //Member 0 must be a Boolean type scalar(LOD),
4727 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4728 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4729 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4730 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4731 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4732 std::vector<spv::Id> members;
4733 members.push_back(resultType());
4734 for (int i = 0; i < 5; i++) {
4735 members.push_back(builder.getContainedTypeId(resultStructType, i));
4736 }
4737 spv::Id resType = builder.makeStructType(members, "ResType");
4738
4739 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004740 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4741 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004742
4743 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4744 for (int i = 0; i < 5; i++) {
4745 builder.clearAccessChain();
4746 builder.setAccessChainLValue(resultStruct);
4747
4748 //Accessing to a struct we created, no coherent flag is set
4749 spv::Builder::AccessChain::CoherentFlags flags;
4750 flags.clear();
4751
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004752 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004753 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4754 }
4755 return builder.createCompositeExtract(res, resultType(), 0);
4756 }
4757#endif
4758
John Kessenich65336482016-06-16 14:06:26 -06004759 // projective component (might not to move)
4760 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4761 // are divided by the last component of P."
4762 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4763 // unused components will appear after all used components."
4764 if (cracked.proj) {
4765 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4766 int projTargetComp;
4767 switch (sampler.dim) {
4768 case glslang::Esd1D: projTargetComp = 1; break;
4769 case glslang::Esd2D: projTargetComp = 2; break;
4770 case glslang::EsdRect: projTargetComp = 2; break;
4771 default: projTargetComp = projSourceComp; break;
4772 }
4773 // copy the projective coordinate if we have to
4774 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004775 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004776 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4777 projSourceComp);
4778 params.coords = builder.createCompositeInsert(projComp, params.coords,
4779 builder.getTypeId(params.coords), projTargetComp);
4780 }
4781 }
4782
Jeff Bolz36831c92018-09-05 10:11:41 -05004783 // nonprivate
4784 if (imageType.getQualifier().nonprivate) {
4785 params.nonprivate = true;
4786 }
4787
4788 // volatile
4789 if (imageType.getQualifier().volatil) {
4790 params.volatil = true;
4791 }
4792
St0fFa1184dd2018-04-09 21:08:14 +02004793 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004794 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4795 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004796 );
LoopDawg4425f242018-02-18 11:40:01 -07004797
4798 if (components != node->getType().getVectorSize())
4799 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4800
4801 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004802}
4803
4804spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4805{
4806 // Grab the function's pointer from the previously created function
4807 spv::Function* function = functionMap[node->getName().c_str()];
4808 if (! function)
4809 return 0;
4810
4811 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4812 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4813
4814 // See comments in makeFunctions() for details about the semantics for parameter passing.
4815 //
4816 // These imply we need a four step process:
4817 // 1. Evaluate the arguments
4818 // 2. Allocate and make copies of in, out, and inout arguments
4819 // 3. Make the call
4820 // 4. Copy back the results
4821
John Kessenichd3ed90b2018-05-04 11:43:03 -06004822 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004823 std::vector<spv::Builder::AccessChain> lValues;
4824 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004825 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004826 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004827 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004828 // build l-value
4829 builder.clearAccessChain();
4830 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004831 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004832 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004833 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004834 // save l-value
4835 lValues.push_back(builder.getAccessChain());
4836 } else {
4837 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004838 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004839 }
4840 }
4841
4842 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4843 // copy the original into that space.
4844 //
4845 // Also, build up the list of actual arguments to pass in for the call
4846 int lValueCount = 0;
4847 int rValueCount = 0;
4848 std::vector<spv::Id> spvArgs;
4849 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4850 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004851 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004852 builder.setAccessChain(lValues[lValueCount]);
4853 arg = builder.accessChainGetLValue();
4854 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004855 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004856 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004857 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004858 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4859 // need to copy the input into output space
4860 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004861 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004862 builder.clearAccessChain();
4863 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004864 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004865 }
4866 ++lValueCount;
4867 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004868 // process r-value, which involves a copy for a type mismatch
4869 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4870 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4871 builder.clearAccessChain();
4872 builder.setAccessChainLValue(argCopy);
4873 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4874 arg = builder.createLoad(argCopy);
4875 } else
4876 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004877 ++rValueCount;
4878 }
4879 spvArgs.push_back(arg);
4880 }
4881
4882 // 3. Make the call.
4883 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004884 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004885
4886 // 4. Copy back out an "out" arguments.
4887 lValueCount = 0;
4888 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004889 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004890 ++lValueCount;
4891 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004892 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4893 spv::Id copy = builder.createLoad(spvArgs[a]);
4894 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004895 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004896 }
4897 ++lValueCount;
4898 }
4899 }
4900
4901 return result;
4902}
4903
4904// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004905spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004906 spv::Id typeId, spv::Id left, spv::Id right,
4907 glslang::TBasicType typeProxy, bool reduceComparison)
4908{
John Kessenich66011cb2018-03-06 16:12:04 -07004909 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4910 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004911 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004912
4913 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004914 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004915 bool comparison = false;
4916
4917 switch (op) {
4918 case glslang::EOpAdd:
4919 case glslang::EOpAddAssign:
4920 if (isFloat)
4921 binOp = spv::OpFAdd;
4922 else
4923 binOp = spv::OpIAdd;
4924 break;
4925 case glslang::EOpSub:
4926 case glslang::EOpSubAssign:
4927 if (isFloat)
4928 binOp = spv::OpFSub;
4929 else
4930 binOp = spv::OpISub;
4931 break;
4932 case glslang::EOpMul:
4933 case glslang::EOpMulAssign:
4934 if (isFloat)
4935 binOp = spv::OpFMul;
4936 else
4937 binOp = spv::OpIMul;
4938 break;
4939 case glslang::EOpVectorTimesScalar:
4940 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004941 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004942 if (builder.isVector(right))
4943 std::swap(left, right);
4944 assert(builder.isScalar(right));
4945 needMatchingVectors = false;
4946 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004947 } else if (isFloat)
4948 binOp = spv::OpFMul;
4949 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004950 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004951 break;
4952 case glslang::EOpVectorTimesMatrix:
4953 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004954 binOp = spv::OpVectorTimesMatrix;
4955 break;
4956 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004957 binOp = spv::OpMatrixTimesVector;
4958 break;
4959 case glslang::EOpMatrixTimesScalar:
4960 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004961 binOp = spv::OpMatrixTimesScalar;
4962 break;
4963 case glslang::EOpMatrixTimesMatrix:
4964 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004965 binOp = spv::OpMatrixTimesMatrix;
4966 break;
4967 case glslang::EOpOuterProduct:
4968 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004969 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004970 break;
4971
4972 case glslang::EOpDiv:
4973 case glslang::EOpDivAssign:
4974 if (isFloat)
4975 binOp = spv::OpFDiv;
4976 else if (isUnsigned)
4977 binOp = spv::OpUDiv;
4978 else
4979 binOp = spv::OpSDiv;
4980 break;
4981 case glslang::EOpMod:
4982 case glslang::EOpModAssign:
4983 if (isFloat)
4984 binOp = spv::OpFMod;
4985 else if (isUnsigned)
4986 binOp = spv::OpUMod;
4987 else
4988 binOp = spv::OpSMod;
4989 break;
4990 case glslang::EOpRightShift:
4991 case glslang::EOpRightShiftAssign:
4992 if (isUnsigned)
4993 binOp = spv::OpShiftRightLogical;
4994 else
4995 binOp = spv::OpShiftRightArithmetic;
4996 break;
4997 case glslang::EOpLeftShift:
4998 case glslang::EOpLeftShiftAssign:
4999 binOp = spv::OpShiftLeftLogical;
5000 break;
5001 case glslang::EOpAnd:
5002 case glslang::EOpAndAssign:
5003 binOp = spv::OpBitwiseAnd;
5004 break;
5005 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005006 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005007 binOp = spv::OpLogicalAnd;
5008 break;
5009 case glslang::EOpInclusiveOr:
5010 case glslang::EOpInclusiveOrAssign:
5011 binOp = spv::OpBitwiseOr;
5012 break;
5013 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005014 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005015 binOp = spv::OpLogicalOr;
5016 break;
5017 case glslang::EOpExclusiveOr:
5018 case glslang::EOpExclusiveOrAssign:
5019 binOp = spv::OpBitwiseXor;
5020 break;
5021 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005022 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005023 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005024 break;
5025
5026 case glslang::EOpLessThan:
5027 case glslang::EOpGreaterThan:
5028 case glslang::EOpLessThanEqual:
5029 case glslang::EOpGreaterThanEqual:
5030 case glslang::EOpEqual:
5031 case glslang::EOpNotEqual:
5032 case glslang::EOpVectorEqual:
5033 case glslang::EOpVectorNotEqual:
5034 comparison = true;
5035 break;
5036 default:
5037 break;
5038 }
5039
John Kessenich7c1aa102015-10-15 13:29:11 -06005040 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005041 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005042 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005043 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5044 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005045 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005046
5047 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005048 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005049 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005050
qining25262b32016-05-06 17:25:16 -04005051 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005052 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005053 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005054 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005055 }
5056
5057 if (! comparison)
5058 return 0;
5059
John Kessenich7c1aa102015-10-15 13:29:11 -06005060 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005061
John Kessenich4583b612016-08-07 19:14:22 -06005062 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005063 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5064 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005065 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005066 return result;
5067 }
John Kessenich140f3df2015-06-26 16:58:36 -06005068
5069 switch (op) {
5070 case glslang::EOpLessThan:
5071 if (isFloat)
5072 binOp = spv::OpFOrdLessThan;
5073 else if (isUnsigned)
5074 binOp = spv::OpULessThan;
5075 else
5076 binOp = spv::OpSLessThan;
5077 break;
5078 case glslang::EOpGreaterThan:
5079 if (isFloat)
5080 binOp = spv::OpFOrdGreaterThan;
5081 else if (isUnsigned)
5082 binOp = spv::OpUGreaterThan;
5083 else
5084 binOp = spv::OpSGreaterThan;
5085 break;
5086 case glslang::EOpLessThanEqual:
5087 if (isFloat)
5088 binOp = spv::OpFOrdLessThanEqual;
5089 else if (isUnsigned)
5090 binOp = spv::OpULessThanEqual;
5091 else
5092 binOp = spv::OpSLessThanEqual;
5093 break;
5094 case glslang::EOpGreaterThanEqual:
5095 if (isFloat)
5096 binOp = spv::OpFOrdGreaterThanEqual;
5097 else if (isUnsigned)
5098 binOp = spv::OpUGreaterThanEqual;
5099 else
5100 binOp = spv::OpSGreaterThanEqual;
5101 break;
5102 case glslang::EOpEqual:
5103 case glslang::EOpVectorEqual:
5104 if (isFloat)
5105 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005106 else if (isBool)
5107 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005108 else
5109 binOp = spv::OpIEqual;
5110 break;
5111 case glslang::EOpNotEqual:
5112 case glslang::EOpVectorNotEqual:
5113 if (isFloat)
5114 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005115 else if (isBool)
5116 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005117 else
5118 binOp = spv::OpINotEqual;
5119 break;
5120 default:
5121 break;
5122 }
5123
qining25262b32016-05-06 17:25:16 -04005124 if (binOp != spv::OpNop) {
5125 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005126 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005127 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005128 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005129 }
John Kessenich140f3df2015-06-26 16:58:36 -06005130
5131 return 0;
5132}
5133
John Kessenich04bb8a02015-12-12 12:28:14 -07005134//
5135// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5136// These can be any of:
5137//
5138// matrix * scalar
5139// scalar * matrix
5140// matrix * matrix linear algebraic
5141// matrix * vector
5142// vector * matrix
5143// matrix * matrix componentwise
5144// matrix op matrix op in {+, -, /}
5145// matrix op scalar op in {+, -, /}
5146// scalar op matrix op in {+, -, /}
5147//
John Kessenichead86222018-03-28 18:01:20 -06005148spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5149 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005150{
5151 bool firstClass = true;
5152
5153 // First, handle first-class matrix operations (* and matrix/scalar)
5154 switch (op) {
5155 case spv::OpFDiv:
5156 if (builder.isMatrix(left) && builder.isScalar(right)) {
5157 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005158 spv::Id resultType = builder.getTypeId(right);
5159 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005160 op = spv::OpMatrixTimesScalar;
5161 } else
5162 firstClass = false;
5163 break;
5164 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005165 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005166 std::swap(left, right);
5167 assert(builder.isScalar(right));
5168 break;
5169 case spv::OpVectorTimesMatrix:
5170 assert(builder.isVector(left));
5171 assert(builder.isMatrix(right));
5172 break;
5173 case spv::OpMatrixTimesVector:
5174 assert(builder.isMatrix(left));
5175 assert(builder.isVector(right));
5176 break;
5177 case spv::OpMatrixTimesMatrix:
5178 assert(builder.isMatrix(left));
5179 assert(builder.isMatrix(right));
5180 break;
5181 default:
5182 firstClass = false;
5183 break;
5184 }
5185
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005186 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5187 firstClass = true;
5188
qining25262b32016-05-06 17:25:16 -04005189 if (firstClass) {
5190 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005191 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005192 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005193 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005194 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005195
LoopDawg592860c2016-06-09 08:57:35 -06005196 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005197 // The result type of all of them is the same type as the (a) matrix operand.
5198 // The algorithm is to:
5199 // - break the matrix(es) into vectors
5200 // - smear any scalar to a vector
5201 // - do vector operations
5202 // - make a matrix out the vector results
5203 switch (op) {
5204 case spv::OpFAdd:
5205 case spv::OpFSub:
5206 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005207 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005208 case spv::OpFMul:
5209 {
5210 // one time set up...
5211 bool leftMat = builder.isMatrix(left);
5212 bool rightMat = builder.isMatrix(right);
5213 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5214 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5215 spv::Id scalarType = builder.getScalarTypeId(typeId);
5216 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5217 std::vector<spv::Id> results;
5218 spv::Id smearVec = spv::NoResult;
5219 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005220 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005221 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005222 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005223
5224 // do each vector op
5225 for (unsigned int c = 0; c < numCols; ++c) {
5226 std::vector<unsigned int> indexes;
5227 indexes.push_back(c);
5228 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5229 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005230 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005231 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005232 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005233 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005234 }
5235
5236 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005237 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005238 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005239 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005240 }
5241 default:
5242 assert(0);
5243 return spv::NoResult;
5244 }
5245}
5246
John Kessenichead86222018-03-28 18:01:20 -06005247spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5248 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005249{
5250 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005251 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005252 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005253 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5254 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005255
5256 switch (op) {
5257 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005258 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005259 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005260 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005261 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005262 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005263 unaryOp = spv::OpSNegate;
5264 break;
5265
5266 case glslang::EOpLogicalNot:
5267 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005268 unaryOp = spv::OpLogicalNot;
5269 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 case glslang::EOpBitwiseNot:
5271 unaryOp = spv::OpNot;
5272 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005273
John Kessenich140f3df2015-06-26 16:58:36 -06005274 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005275 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005276 break;
5277 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005278 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005279 break;
5280 case glslang::EOpTranspose:
5281 unaryOp = spv::OpTranspose;
5282 break;
5283
5284 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005288 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005289 break;
5290 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005291 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005292 break;
5293 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005294 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005295 break;
5296 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005297 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005298 break;
5299 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005300 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005301 break;
5302 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005303 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005304 break;
5305 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005306 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005307 break;
5308
5309 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005310 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005311 break;
5312 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005313 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 break;
5315 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005316 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005317 break;
5318 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005319 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005320 break;
5321 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005322 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327
5328 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334
5335 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005336 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005337 break;
5338 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005339 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 break;
5341 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005342 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 break;
5344 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005345 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005346 break;
5347 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005348 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005349 break;
5350 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005351 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005352 break;
5353
5354 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005355 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005356 break;
5357 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005358 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005359 break;
5360 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005361 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005362 break;
5363 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005364 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005365 break;
5366 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005367 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005368 break;
5369 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005370 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005371 break;
5372
5373 case glslang::EOpIsNan:
5374 unaryOp = spv::OpIsNan;
5375 break;
5376 case glslang::EOpIsInf:
5377 unaryOp = spv::OpIsInf;
5378 break;
LoopDawg592860c2016-06-09 08:57:35 -06005379 case glslang::EOpIsFinite:
5380 unaryOp = spv::OpIsFinite;
5381 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005382
Rex Xucbc426e2015-12-15 16:03:10 +08005383 case glslang::EOpFloatBitsToInt:
5384 case glslang::EOpFloatBitsToUint:
5385 case glslang::EOpIntBitsToFloat:
5386 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005387 case glslang::EOpDoubleBitsToInt64:
5388 case glslang::EOpDoubleBitsToUint64:
5389 case glslang::EOpInt64BitsToDouble:
5390 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005391 case glslang::EOpFloat16BitsToInt16:
5392 case glslang::EOpFloat16BitsToUint16:
5393 case glslang::EOpInt16BitsToFloat16:
5394 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005395 unaryOp = spv::OpBitcast;
5396 break;
5397
John Kessenich140f3df2015-06-26 16:58:36 -06005398 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005399 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005400 break;
5401 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005402 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005403 break;
5404 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005405 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005406 break;
5407 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005408 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005409 break;
5410 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005411 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005412 break;
5413 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005414 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005416 case glslang::EOpPackSnorm4x8:
5417 libCall = spv::GLSLstd450PackSnorm4x8;
5418 break;
5419 case glslang::EOpUnpackSnorm4x8:
5420 libCall = spv::GLSLstd450UnpackSnorm4x8;
5421 break;
5422 case glslang::EOpPackUnorm4x8:
5423 libCall = spv::GLSLstd450PackUnorm4x8;
5424 break;
5425 case glslang::EOpUnpackUnorm4x8:
5426 libCall = spv::GLSLstd450UnpackUnorm4x8;
5427 break;
5428 case glslang::EOpPackDouble2x32:
5429 libCall = spv::GLSLstd450PackDouble2x32;
5430 break;
5431 case glslang::EOpUnpackDouble2x32:
5432 libCall = spv::GLSLstd450UnpackDouble2x32;
5433 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005434
Rex Xu8ff43de2016-04-22 16:51:45 +08005435 case glslang::EOpPackInt2x32:
5436 case glslang::EOpUnpackInt2x32:
5437 case glslang::EOpPackUint2x32:
5438 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005439 case glslang::EOpPack16:
5440 case glslang::EOpPack32:
5441 case glslang::EOpPack64:
5442 case glslang::EOpUnpack32:
5443 case glslang::EOpUnpack16:
5444 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005445 case glslang::EOpPackInt2x16:
5446 case glslang::EOpUnpackInt2x16:
5447 case glslang::EOpPackUint2x16:
5448 case glslang::EOpUnpackUint2x16:
5449 case glslang::EOpPackInt4x16:
5450 case glslang::EOpUnpackInt4x16:
5451 case glslang::EOpPackUint4x16:
5452 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005453 case glslang::EOpPackFloat2x16:
5454 case glslang::EOpUnpackFloat2x16:
5455 unaryOp = spv::OpBitcast;
5456 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005457
John Kessenich140f3df2015-06-26 16:58:36 -06005458 case glslang::EOpDPdx:
5459 unaryOp = spv::OpDPdx;
5460 break;
5461 case glslang::EOpDPdy:
5462 unaryOp = spv::OpDPdy;
5463 break;
5464 case glslang::EOpFwidth:
5465 unaryOp = spv::OpFwidth;
5466 break;
5467 case glslang::EOpDPdxFine:
5468 unaryOp = spv::OpDPdxFine;
5469 break;
5470 case glslang::EOpDPdyFine:
5471 unaryOp = spv::OpDPdyFine;
5472 break;
5473 case glslang::EOpFwidthFine:
5474 unaryOp = spv::OpFwidthFine;
5475 break;
5476 case glslang::EOpDPdxCoarse:
5477 unaryOp = spv::OpDPdxCoarse;
5478 break;
5479 case glslang::EOpDPdyCoarse:
5480 unaryOp = spv::OpDPdyCoarse;
5481 break;
5482 case glslang::EOpFwidthCoarse:
5483 unaryOp = spv::OpFwidthCoarse;
5484 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005485 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005486#ifdef AMD_EXTENSIONS
5487 if (typeProxy == glslang::EbtFloat16)
5488 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5489#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005490 libCall = spv::GLSLstd450InterpolateAtCentroid;
5491 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 case glslang::EOpAny:
5493 unaryOp = spv::OpAny;
5494 break;
5495 case glslang::EOpAll:
5496 unaryOp = spv::OpAll;
5497 break;
5498
5499 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005500 if (isFloat)
5501 libCall = spv::GLSLstd450FAbs;
5502 else
5503 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 break;
5505 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 if (isFloat)
5507 libCall = spv::GLSLstd450FSign;
5508 else
5509 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511
John Kessenichfc51d282015-08-19 13:34:18 -06005512 case glslang::EOpAtomicCounterIncrement:
5513 case glslang::EOpAtomicCounterDecrement:
5514 case glslang::EOpAtomicCounter:
5515 {
5516 // Handle all of the atomics in one place, in createAtomicOperation()
5517 std::vector<spv::Id> operands;
5518 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005519 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005520 }
5521
John Kessenichfc51d282015-08-19 13:34:18 -06005522 case glslang::EOpBitFieldReverse:
5523 unaryOp = spv::OpBitReverse;
5524 break;
5525 case glslang::EOpBitCount:
5526 unaryOp = spv::OpBitCount;
5527 break;
5528 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005529 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005530 break;
5531 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005532 if (isUnsigned)
5533 libCall = spv::GLSLstd450FindUMsb;
5534 else
5535 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005536 break;
5537
Rex Xu574ab042016-04-14 16:53:07 +08005538 case glslang::EOpBallot:
5539 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005540 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005541 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005542 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005543#ifdef AMD_EXTENSIONS
5544 case glslang::EOpMinInvocations:
5545 case glslang::EOpMaxInvocations:
5546 case glslang::EOpAddInvocations:
5547 case glslang::EOpMinInvocationsNonUniform:
5548 case glslang::EOpMaxInvocationsNonUniform:
5549 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005550 case glslang::EOpMinInvocationsInclusiveScan:
5551 case glslang::EOpMaxInvocationsInclusiveScan:
5552 case glslang::EOpAddInvocationsInclusiveScan:
5553 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5554 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5555 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5556 case glslang::EOpMinInvocationsExclusiveScan:
5557 case glslang::EOpMaxInvocationsExclusiveScan:
5558 case glslang::EOpAddInvocationsExclusiveScan:
5559 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5560 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5561 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005562#endif
Rex Xu51596642016-09-21 18:56:12 +08005563 {
5564 std::vector<spv::Id> operands;
5565 operands.push_back(operand);
5566 return createInvocationsOperation(op, typeId, operands, typeProxy);
5567 }
John Kessenich66011cb2018-03-06 16:12:04 -07005568 case glslang::EOpSubgroupAll:
5569 case glslang::EOpSubgroupAny:
5570 case glslang::EOpSubgroupAllEqual:
5571 case glslang::EOpSubgroupBroadcastFirst:
5572 case glslang::EOpSubgroupBallot:
5573 case glslang::EOpSubgroupInverseBallot:
5574 case glslang::EOpSubgroupBallotBitCount:
5575 case glslang::EOpSubgroupBallotInclusiveBitCount:
5576 case glslang::EOpSubgroupBallotExclusiveBitCount:
5577 case glslang::EOpSubgroupBallotFindLSB:
5578 case glslang::EOpSubgroupBallotFindMSB:
5579 case glslang::EOpSubgroupAdd:
5580 case glslang::EOpSubgroupMul:
5581 case glslang::EOpSubgroupMin:
5582 case glslang::EOpSubgroupMax:
5583 case glslang::EOpSubgroupAnd:
5584 case glslang::EOpSubgroupOr:
5585 case glslang::EOpSubgroupXor:
5586 case glslang::EOpSubgroupInclusiveAdd:
5587 case glslang::EOpSubgroupInclusiveMul:
5588 case glslang::EOpSubgroupInclusiveMin:
5589 case glslang::EOpSubgroupInclusiveMax:
5590 case glslang::EOpSubgroupInclusiveAnd:
5591 case glslang::EOpSubgroupInclusiveOr:
5592 case glslang::EOpSubgroupInclusiveXor:
5593 case glslang::EOpSubgroupExclusiveAdd:
5594 case glslang::EOpSubgroupExclusiveMul:
5595 case glslang::EOpSubgroupExclusiveMin:
5596 case glslang::EOpSubgroupExclusiveMax:
5597 case glslang::EOpSubgroupExclusiveAnd:
5598 case glslang::EOpSubgroupExclusiveOr:
5599 case glslang::EOpSubgroupExclusiveXor:
5600 case glslang::EOpSubgroupQuadSwapHorizontal:
5601 case glslang::EOpSubgroupQuadSwapVertical:
5602 case glslang::EOpSubgroupQuadSwapDiagonal: {
5603 std::vector<spv::Id> operands;
5604 operands.push_back(operand);
5605 return createSubgroupOperation(op, typeId, operands, typeProxy);
5606 }
Rex Xu9d93a232016-05-05 12:30:44 +08005607#ifdef AMD_EXTENSIONS
5608 case glslang::EOpMbcnt:
5609 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5610 libCall = spv::MbcntAMD;
5611 break;
5612
5613 case glslang::EOpCubeFaceIndex:
5614 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5615 libCall = spv::CubeFaceIndexAMD;
5616 break;
5617
5618 case glslang::EOpCubeFaceCoord:
5619 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5620 libCall = spv::CubeFaceCoordAMD;
5621 break;
5622#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005623#ifdef NV_EXTENSIONS
5624 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005625 unaryOp = spv::OpGroupNonUniformPartitionNV;
5626 break;
5627#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005628 case glslang::EOpConstructReference:
5629 unaryOp = spv::OpBitcast;
5630 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005631
5632 case glslang::EOpCopyObject:
5633 unaryOp = spv::OpCopyObject;
5634 break;
5635
John Kessenich140f3df2015-06-26 16:58:36 -06005636 default:
5637 return 0;
5638 }
5639
5640 spv::Id id;
5641 if (libCall >= 0) {
5642 std::vector<spv::Id> args;
5643 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005644 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005645 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005646 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005647 }
John Kessenich140f3df2015-06-26 16:58:36 -06005648
John Kessenichead86222018-03-28 18:01:20 -06005649 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005650 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005651 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005652}
5653
John Kessenich7a53f762016-01-20 11:19:27 -07005654// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005655spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5656 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005657{
5658 // Handle unary operations vector by vector.
5659 // The result type is the same type as the original type.
5660 // The algorithm is to:
5661 // - break the matrix into vectors
5662 // - apply the operation to each vector
5663 // - make a matrix out the vector results
5664
5665 // get the types sorted out
5666 int numCols = builder.getNumColumns(operand);
5667 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005668 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5669 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005670 std::vector<spv::Id> results;
5671
5672 // do each vector op
5673 for (int c = 0; c < numCols; ++c) {
5674 std::vector<unsigned int> indexes;
5675 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005676 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5677 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005678 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005679 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005680 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005681 }
5682
5683 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005684 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005685 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005686 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005687}
5688
John Kessenichad7645f2018-06-04 19:11:25 -06005689// For converting integers where both the bitwidth and the signedness could
5690// change, but only do the width change here. The caller is still responsible
5691// for the signedness conversion.
5692spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005693{
John Kessenichad7645f2018-06-04 19:11:25 -06005694 // Get the result type width, based on the type to convert to.
5695 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005696 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005697 case glslang::EOpConvInt16ToUint8:
5698 case glslang::EOpConvIntToUint8:
5699 case glslang::EOpConvInt64ToUint8:
5700 case glslang::EOpConvUint16ToInt8:
5701 case glslang::EOpConvUintToInt8:
5702 case glslang::EOpConvUint64ToInt8:
5703 width = 8;
5704 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005705 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005706 case glslang::EOpConvIntToUint16:
5707 case glslang::EOpConvInt64ToUint16:
5708 case glslang::EOpConvUint8ToInt16:
5709 case glslang::EOpConvUintToInt16:
5710 case glslang::EOpConvUint64ToInt16:
5711 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005712 break;
5713 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005714 case glslang::EOpConvInt16ToUint:
5715 case glslang::EOpConvInt64ToUint:
5716 case glslang::EOpConvUint8ToInt:
5717 case glslang::EOpConvUint16ToInt:
5718 case glslang::EOpConvUint64ToInt:
5719 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005720 break;
5721 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005722 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005723 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005724 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005725 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005726 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005727 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005728 break;
5729
5730 default:
5731 assert(false && "Default missing");
5732 break;
5733 }
5734
John Kessenichad7645f2018-06-04 19:11:25 -06005735 // Get the conversion operation and result type,
5736 // based on the target width, but the source type.
5737 spv::Id type = spv::NoType;
5738 spv::Op convOp = spv::OpNop;
5739 switch(op) {
5740 case glslang::EOpConvInt8ToUint16:
5741 case glslang::EOpConvInt8ToUint:
5742 case glslang::EOpConvInt8ToUint64:
5743 case glslang::EOpConvInt16ToUint8:
5744 case glslang::EOpConvInt16ToUint:
5745 case glslang::EOpConvInt16ToUint64:
5746 case glslang::EOpConvIntToUint8:
5747 case glslang::EOpConvIntToUint16:
5748 case glslang::EOpConvIntToUint64:
5749 case glslang::EOpConvInt64ToUint8:
5750 case glslang::EOpConvInt64ToUint16:
5751 case glslang::EOpConvInt64ToUint:
5752 convOp = spv::OpSConvert;
5753 type = builder.makeIntType(width);
5754 break;
5755 default:
5756 convOp = spv::OpUConvert;
5757 type = builder.makeUintType(width);
5758 break;
5759 }
5760
John Kessenich66011cb2018-03-06 16:12:04 -07005761 if (vectorSize > 0)
5762 type = builder.makeVectorType(type, vectorSize);
5763
John Kessenichad7645f2018-06-04 19:11:25 -06005764 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005765}
5766
John Kessenichead86222018-03-28 18:01:20 -06005767spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5768 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005769{
5770 spv::Op convOp = spv::OpNop;
5771 spv::Id zero = 0;
5772 spv::Id one = 0;
5773
5774 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5775
5776 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005777 case glslang::EOpConvInt8ToBool:
5778 case glslang::EOpConvUint8ToBool:
5779 zero = builder.makeUint8Constant(0);
5780 zero = makeSmearedConstant(zero, vectorSize);
5781 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005782 case glslang::EOpConvInt16ToBool:
5783 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005784 zero = builder.makeUint16Constant(0);
5785 zero = makeSmearedConstant(zero, vectorSize);
5786 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5787 case glslang::EOpConvIntToBool:
5788 case glslang::EOpConvUintToBool:
5789 zero = builder.makeUintConstant(0);
5790 zero = makeSmearedConstant(zero, vectorSize);
5791 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5792 case glslang::EOpConvInt64ToBool:
5793 case glslang::EOpConvUint64ToBool:
5794 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005795 zero = makeSmearedConstant(zero, vectorSize);
5796 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5797
5798 case glslang::EOpConvFloatToBool:
5799 zero = builder.makeFloatConstant(0.0F);
5800 zero = makeSmearedConstant(zero, vectorSize);
5801 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5802
5803 case glslang::EOpConvDoubleToBool:
5804 zero = builder.makeDoubleConstant(0.0);
5805 zero = makeSmearedConstant(zero, vectorSize);
5806 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5807
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005808 case glslang::EOpConvFloat16ToBool:
5809 zero = builder.makeFloat16Constant(0.0F);
5810 zero = makeSmearedConstant(zero, vectorSize);
5811 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005812
John Kessenich140f3df2015-06-26 16:58:36 -06005813 case glslang::EOpConvBoolToFloat:
5814 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005815 zero = builder.makeFloatConstant(0.0F);
5816 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005818
John Kessenich140f3df2015-06-26 16:58:36 -06005819 case glslang::EOpConvBoolToDouble:
5820 convOp = spv::OpSelect;
5821 zero = builder.makeDoubleConstant(0.0);
5822 one = builder.makeDoubleConstant(1.0);
5823 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005824
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005825 case glslang::EOpConvBoolToFloat16:
5826 convOp = spv::OpSelect;
5827 zero = builder.makeFloat16Constant(0.0F);
5828 one = builder.makeFloat16Constant(1.0F);
5829 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005830
5831 case glslang::EOpConvBoolToInt8:
5832 zero = builder.makeInt8Constant(0);
5833 one = builder.makeInt8Constant(1);
5834 convOp = spv::OpSelect;
5835 break;
5836
5837 case glslang::EOpConvBoolToUint8:
5838 zero = builder.makeUint8Constant(0);
5839 one = builder.makeUint8Constant(1);
5840 convOp = spv::OpSelect;
5841 break;
5842
5843 case glslang::EOpConvBoolToInt16:
5844 zero = builder.makeInt16Constant(0);
5845 one = builder.makeInt16Constant(1);
5846 convOp = spv::OpSelect;
5847 break;
5848
5849 case glslang::EOpConvBoolToUint16:
5850 zero = builder.makeUint16Constant(0);
5851 one = builder.makeUint16Constant(1);
5852 convOp = spv::OpSelect;
5853 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005854
John Kessenich140f3df2015-06-26 16:58:36 -06005855 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005856 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005857 if (op == glslang::EOpConvBoolToInt64)
5858 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005859 else
5860 zero = builder.makeIntConstant(0);
5861
5862 if (op == glslang::EOpConvBoolToInt64)
5863 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005864 else
5865 one = builder.makeIntConstant(1);
5866
John Kessenich140f3df2015-06-26 16:58:36 -06005867 convOp = spv::OpSelect;
5868 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005869
John Kessenich140f3df2015-06-26 16:58:36 -06005870 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005871 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005872 if (op == glslang::EOpConvBoolToUint64)
5873 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005874 else
5875 zero = builder.makeUintConstant(0);
5876
5877 if (op == glslang::EOpConvBoolToUint64)
5878 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005879 else
5880 one = builder.makeUintConstant(1);
5881
John Kessenich140f3df2015-06-26 16:58:36 -06005882 convOp = spv::OpSelect;
5883 break;
5884
John Kessenich66011cb2018-03-06 16:12:04 -07005885 case glslang::EOpConvInt8ToFloat16:
5886 case glslang::EOpConvInt8ToFloat:
5887 case glslang::EOpConvInt8ToDouble:
5888 case glslang::EOpConvInt16ToFloat16:
5889 case glslang::EOpConvInt16ToFloat:
5890 case glslang::EOpConvInt16ToDouble:
5891 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005892 case glslang::EOpConvIntToFloat:
5893 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005894 case glslang::EOpConvInt64ToFloat:
5895 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005896 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005897 convOp = spv::OpConvertSToF;
5898 break;
5899
John Kessenich66011cb2018-03-06 16:12:04 -07005900 case glslang::EOpConvUint8ToFloat16:
5901 case glslang::EOpConvUint8ToFloat:
5902 case glslang::EOpConvUint8ToDouble:
5903 case glslang::EOpConvUint16ToFloat16:
5904 case glslang::EOpConvUint16ToFloat:
5905 case glslang::EOpConvUint16ToDouble:
5906 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005907 case glslang::EOpConvUintToFloat:
5908 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005909 case glslang::EOpConvUint64ToFloat:
5910 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005911 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005912 convOp = spv::OpConvertUToF;
5913 break;
5914
5915 case glslang::EOpConvDoubleToFloat:
5916 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005917 case glslang::EOpConvDoubleToFloat16:
5918 case glslang::EOpConvFloat16ToDouble:
5919 case glslang::EOpConvFloatToFloat16:
5920 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005921 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005922 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005923 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005924 break;
5925
John Kessenich66011cb2018-03-06 16:12:04 -07005926 case glslang::EOpConvFloat16ToInt8:
5927 case glslang::EOpConvFloatToInt8:
5928 case glslang::EOpConvDoubleToInt8:
5929 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005930 case glslang::EOpConvFloatToInt16:
5931 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005932 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005933 case glslang::EOpConvFloatToInt:
5934 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005935 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005936 case glslang::EOpConvFloatToInt64:
5937 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005938 convOp = spv::OpConvertFToS;
5939 break;
5940
John Kessenich66011cb2018-03-06 16:12:04 -07005941 case glslang::EOpConvUint8ToInt8:
5942 case glslang::EOpConvInt8ToUint8:
5943 case glslang::EOpConvUint16ToInt16:
5944 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005945 case glslang::EOpConvUintToInt:
5946 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005947 case glslang::EOpConvUint64ToInt64:
5948 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005949 if (builder.isInSpecConstCodeGenMode()) {
5950 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005951 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5952 zero = builder.makeUint8Constant(0);
5953 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005954 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005955 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5956 zero = builder.makeUint64Constant(0);
5957 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005958 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005959 }
qining189b2032016-04-12 23:16:20 -04005960 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005961 // Use OpIAdd, instead of OpBitcast to do the conversion when
5962 // generating for OpSpecConstantOp instruction.
5963 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5964 }
5965 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005966 convOp = spv::OpBitcast;
5967 break;
5968
John Kessenich66011cb2018-03-06 16:12:04 -07005969 case glslang::EOpConvFloat16ToUint8:
5970 case glslang::EOpConvFloatToUint8:
5971 case glslang::EOpConvDoubleToUint8:
5972 case glslang::EOpConvFloat16ToUint16:
5973 case glslang::EOpConvFloatToUint16:
5974 case glslang::EOpConvDoubleToUint16:
5975 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005976 case glslang::EOpConvFloatToUint:
5977 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005978 case glslang::EOpConvFloatToUint64:
5979 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005980 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005981 convOp = spv::OpConvertFToU;
5982 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005983
John Kessenich66011cb2018-03-06 16:12:04 -07005984 case glslang::EOpConvInt8ToInt16:
5985 case glslang::EOpConvInt8ToInt:
5986 case glslang::EOpConvInt8ToInt64:
5987 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005988 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005989 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005990 case glslang::EOpConvIntToInt8:
5991 case glslang::EOpConvIntToInt16:
5992 case glslang::EOpConvIntToInt64:
5993 case glslang::EOpConvInt64ToInt8:
5994 case glslang::EOpConvInt64ToInt16:
5995 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005996 convOp = spv::OpSConvert;
5997 break;
5998
John Kessenich66011cb2018-03-06 16:12:04 -07005999 case glslang::EOpConvUint8ToUint16:
6000 case glslang::EOpConvUint8ToUint:
6001 case glslang::EOpConvUint8ToUint64:
6002 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006003 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006004 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006005 case glslang::EOpConvUintToUint8:
6006 case glslang::EOpConvUintToUint16:
6007 case glslang::EOpConvUintToUint64:
6008 case glslang::EOpConvUint64ToUint8:
6009 case glslang::EOpConvUint64ToUint16:
6010 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006011 convOp = spv::OpUConvert;
6012 break;
6013
John Kessenich66011cb2018-03-06 16:12:04 -07006014 case glslang::EOpConvInt8ToUint16:
6015 case glslang::EOpConvInt8ToUint:
6016 case glslang::EOpConvInt8ToUint64:
6017 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006018 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006019 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006020 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006021 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006022 case glslang::EOpConvIntToUint64:
6023 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006024 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006025 case glslang::EOpConvInt64ToUint:
6026 case glslang::EOpConvUint8ToInt16:
6027 case glslang::EOpConvUint8ToInt:
6028 case glslang::EOpConvUint8ToInt64:
6029 case glslang::EOpConvUint16ToInt8:
6030 case glslang::EOpConvUint16ToInt:
6031 case glslang::EOpConvUint16ToInt64:
6032 case glslang::EOpConvUintToInt8:
6033 case glslang::EOpConvUintToInt16:
6034 case glslang::EOpConvUintToInt64:
6035 case glslang::EOpConvUint64ToInt8:
6036 case glslang::EOpConvUint64ToInt16:
6037 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006038 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006039 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006040
6041 if (builder.isInSpecConstCodeGenMode()) {
6042 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006043 switch(op) {
6044 case glslang::EOpConvInt16ToUint8:
6045 case glslang::EOpConvIntToUint8:
6046 case glslang::EOpConvInt64ToUint8:
6047 case glslang::EOpConvUint16ToInt8:
6048 case glslang::EOpConvUintToInt8:
6049 case glslang::EOpConvUint64ToInt8:
6050 zero = builder.makeUint8Constant(0);
6051 break;
6052 case glslang::EOpConvInt8ToUint16:
6053 case glslang::EOpConvIntToUint16:
6054 case glslang::EOpConvInt64ToUint16:
6055 case glslang::EOpConvUint8ToInt16:
6056 case glslang::EOpConvUintToInt16:
6057 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006058 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006059 break;
6060 case glslang::EOpConvInt8ToUint:
6061 case glslang::EOpConvInt16ToUint:
6062 case glslang::EOpConvInt64ToUint:
6063 case glslang::EOpConvUint8ToInt:
6064 case glslang::EOpConvUint16ToInt:
6065 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006066 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006067 break;
6068 case glslang::EOpConvInt8ToUint64:
6069 case glslang::EOpConvInt16ToUint64:
6070 case glslang::EOpConvIntToUint64:
6071 case glslang::EOpConvUint8ToInt64:
6072 case glslang::EOpConvUint16ToInt64:
6073 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006074 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006075 break;
6076 default:
6077 assert(false && "Default missing");
6078 break;
6079 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006080 zero = makeSmearedConstant(zero, vectorSize);
6081 // Use OpIAdd, instead of OpBitcast to do the conversion when
6082 // generating for OpSpecConstantOp instruction.
6083 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6084 }
6085 // For normal run-time conversion instruction, use OpBitcast.
6086 convOp = spv::OpBitcast;
6087 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006088 case glslang::EOpConvUint64ToPtr:
6089 convOp = spv::OpConvertUToPtr;
6090 break;
6091 case glslang::EOpConvPtrToUint64:
6092 convOp = spv::OpConvertPtrToU;
6093 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006094 default:
6095 break;
6096 }
6097
6098 spv::Id result = 0;
6099 if (convOp == spv::OpNop)
6100 return result;
6101
6102 if (convOp == spv::OpSelect) {
6103 zero = makeSmearedConstant(zero, vectorSize);
6104 one = makeSmearedConstant(one, vectorSize);
6105 result = builder.createTriOp(convOp, destType, operand, one, zero);
6106 } else
6107 result = builder.createUnaryOp(convOp, destType, operand);
6108
John Kessenichead86222018-03-28 18:01:20 -06006109 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006110 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006111 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006112}
6113
6114spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6115{
6116 if (vectorSize == 0)
6117 return constant;
6118
6119 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6120 std::vector<spv::Id> components;
6121 for (int c = 0; c < vectorSize; ++c)
6122 components.push_back(constant);
6123 return builder.makeCompositeConstant(vectorTypeId, components);
6124}
6125
John Kessenich426394d2015-07-23 10:22:48 -06006126// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006127spv::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 -06006128{
6129 spv::Op opCode = spv::OpNop;
6130
6131 switch (op) {
6132 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006133 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006134 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006135 opCode = spv::OpAtomicIAdd;
6136 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006137 case glslang::EOpAtomicCounterSubtract:
6138 opCode = spv::OpAtomicISub;
6139 break;
John Kessenich426394d2015-07-23 10:22:48 -06006140 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006141 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006142 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006143 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006144 break;
6145 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006146 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006147 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006148 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006149 break;
6150 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006151 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006152 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006153 opCode = spv::OpAtomicAnd;
6154 break;
6155 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006156 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006157 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006158 opCode = spv::OpAtomicOr;
6159 break;
6160 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006161 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006162 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006163 opCode = spv::OpAtomicXor;
6164 break;
6165 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006166 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006167 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006168 opCode = spv::OpAtomicExchange;
6169 break;
6170 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006171 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006172 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006173 opCode = spv::OpAtomicCompareExchange;
6174 break;
6175 case glslang::EOpAtomicCounterIncrement:
6176 opCode = spv::OpAtomicIIncrement;
6177 break;
6178 case glslang::EOpAtomicCounterDecrement:
6179 opCode = spv::OpAtomicIDecrement;
6180 break;
6181 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006182 case glslang::EOpImageAtomicLoad:
6183 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006184 opCode = spv::OpAtomicLoad;
6185 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006186 case glslang::EOpAtomicStore:
6187 case glslang::EOpImageAtomicStore:
6188 opCode = spv::OpAtomicStore;
6189 break;
John Kessenich426394d2015-07-23 10:22:48 -06006190 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006191 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006192 break;
6193 }
6194
Rex Xue8fe8b02017-09-26 15:42:56 +08006195 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6196 builder.addCapability(spv::CapabilityInt64Atomics);
6197
John Kessenich426394d2015-07-23 10:22:48 -06006198 // Sort out the operands
6199 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006200 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006201 // - compare-exchange swaps the value and comparator
6202 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006203 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006204 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6205 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6206 spv::Id scopeId;
6207 if (glslangIntermediate->usingVulkanMemoryModel()) {
6208 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6209 } else {
6210 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6211 }
6212 // semantics default to relaxed
6213 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6214 spv::Id semanticsId2 = semanticsId;
6215
6216 pointerId = operands[0];
6217 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6218 // no additional operands
6219 } else if (opCode == spv::OpAtomicCompareExchange) {
6220 compareId = operands[1];
6221 valueId = operands[2];
6222 if (operands.size() > 3) {
6223 scopeId = operands[3];
6224 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6225 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6226 }
6227 } else if (opCode == spv::OpAtomicLoad) {
6228 if (operands.size() > 1) {
6229 scopeId = operands[1];
6230 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6231 }
6232 } else {
6233 // atomic store or RMW
6234 valueId = operands[1];
6235 if (operands.size() > 2) {
6236 scopeId = operands[2];
6237 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6238 }
Rex Xu04db3f52015-09-16 11:44:02 +08006239 }
John Kessenich426394d2015-07-23 10:22:48 -06006240
Jeff Bolz36831c92018-09-05 10:11:41 -05006241 // Check for capabilities
6242 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6243 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6244 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6245 }
John Kessenich426394d2015-07-23 10:22:48 -06006246
Jeff Bolz36831c92018-09-05 10:11:41 -05006247 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6248 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6249 }
John Kessenich48d6e792017-10-06 21:21:48 -06006250
Jeff Bolz36831c92018-09-05 10:11:41 -05006251 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6252 spvAtomicOperands.push_back(pointerId);
6253 spvAtomicOperands.push_back(scopeId);
6254 spvAtomicOperands.push_back(semanticsId);
6255 if (opCode == spv::OpAtomicCompareExchange) {
6256 spvAtomicOperands.push_back(semanticsId2);
6257 spvAtomicOperands.push_back(valueId);
6258 spvAtomicOperands.push_back(compareId);
6259 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6260 spvAtomicOperands.push_back(valueId);
6261 }
John Kessenich48d6e792017-10-06 21:21:48 -06006262
Jeff Bolz36831c92018-09-05 10:11:41 -05006263 if (opCode == spv::OpAtomicStore) {
6264 builder.createNoResultOp(opCode, spvAtomicOperands);
6265 return 0;
6266 } else {
6267 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6268
6269 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6270 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6271 if (op == glslang::EOpAtomicCounterDecrement)
6272 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6273
6274 return resultId;
6275 }
John Kessenich426394d2015-07-23 10:22:48 -06006276}
6277
John Kessenich91cef522016-05-05 16:45:40 -06006278// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006279spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006280{
Corentin Walleze7061422018-08-08 15:20:15 +02006281#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006282 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6283 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006284#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006285
Rex Xu51596642016-09-21 18:56:12 +08006286 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006287 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006288 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6289
chaocf200da82016-12-20 12:44:35 -08006290 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6291 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006292 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6293 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006294 } else if (op == glslang::EOpAnyInvocation ||
6295 op == glslang::EOpAllInvocations ||
6296 op == glslang::EOpAllInvocationsEqual) {
6297 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6298 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006299 } else {
6300 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006301#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006302 if (op == glslang::EOpMinInvocationsNonUniform ||
6303 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006304 op == glslang::EOpAddInvocationsNonUniform ||
6305 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6306 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6307 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6308 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6309 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6310 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006311 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006312#endif
Rex Xu51596642016-09-21 18:56:12 +08006313
Rex Xu9d93a232016-05-05 12:30:44 +08006314#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006315 switch (op) {
6316 case glslang::EOpMinInvocations:
6317 case glslang::EOpMaxInvocations:
6318 case glslang::EOpAddInvocations:
6319 case glslang::EOpMinInvocationsNonUniform:
6320 case glslang::EOpMaxInvocationsNonUniform:
6321 case glslang::EOpAddInvocationsNonUniform:
6322 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006323 break;
6324 case glslang::EOpMinInvocationsInclusiveScan:
6325 case glslang::EOpMaxInvocationsInclusiveScan:
6326 case glslang::EOpAddInvocationsInclusiveScan:
6327 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6328 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6329 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6330 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006331 break;
6332 case glslang::EOpMinInvocationsExclusiveScan:
6333 case glslang::EOpMaxInvocationsExclusiveScan:
6334 case glslang::EOpAddInvocationsExclusiveScan:
6335 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6336 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6337 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6338 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006339 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006340 default:
6341 break;
Rex Xu430ef402016-10-14 17:22:23 +08006342 }
John Kessenich149afc32018-08-14 13:31:43 -06006343 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6344 spvGroupOperands.push_back(scope);
6345 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006346 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006347 spvGroupOperands.push_back(groupOp);
6348 }
Rex Xu9d93a232016-05-05 12:30:44 +08006349#endif
Rex Xu51596642016-09-21 18:56:12 +08006350 }
6351
John Kessenich149afc32018-08-14 13:31:43 -06006352 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6353 spv::IdImmediate op = { true, *opIt };
6354 spvGroupOperands.push_back(op);
6355 }
John Kessenich91cef522016-05-05 16:45:40 -06006356
6357 switch (op) {
6358 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006359 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006360 break;
John Kessenich91cef522016-05-05 16:45:40 -06006361 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006362 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006363 break;
John Kessenich91cef522016-05-05 16:45:40 -06006364 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006365 opCode = spv::OpSubgroupAllEqualKHR;
6366 break;
Rex Xu51596642016-09-21 18:56:12 +08006367 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006368 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +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 break;
6372 case glslang::EOpReadFirstInvocation:
6373 opCode = spv::OpSubgroupFirstInvocationKHR;
6374 break;
6375 case glslang::EOpBallot:
6376 {
6377 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6378 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6379 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6380 //
6381 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6382 //
6383 spv::Id uintType = builder.makeUintType(32);
6384 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6385 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6386
6387 std::vector<spv::Id> components;
6388 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6389 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6390
6391 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6392 return builder.createUnaryOp(spv::OpBitcast, typeId,
6393 builder.createCompositeConstruct(uvec2Type, components));
6394 }
6395
Rex Xu9d93a232016-05-05 12:30:44 +08006396#ifdef AMD_EXTENSIONS
6397 case glslang::EOpMinInvocations:
6398 case glslang::EOpMaxInvocations:
6399 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006400 case glslang::EOpMinInvocationsInclusiveScan:
6401 case glslang::EOpMaxInvocationsInclusiveScan:
6402 case glslang::EOpAddInvocationsInclusiveScan:
6403 case glslang::EOpMinInvocationsExclusiveScan:
6404 case glslang::EOpMaxInvocationsExclusiveScan:
6405 case glslang::EOpAddInvocationsExclusiveScan:
6406 if (op == glslang::EOpMinInvocations ||
6407 op == glslang::EOpMinInvocationsInclusiveScan ||
6408 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006409 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006410 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006411 else {
6412 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006413 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006414 else
Rex Xu51596642016-09-21 18:56:12 +08006415 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006416 }
Rex Xu430ef402016-10-14 17:22:23 +08006417 } else if (op == glslang::EOpMaxInvocations ||
6418 op == glslang::EOpMaxInvocationsInclusiveScan ||
6419 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006420 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006421 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006422 else {
6423 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006424 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006425 else
Rex Xu51596642016-09-21 18:56:12 +08006426 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006427 }
6428 } else {
6429 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006430 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006431 else
Rex Xu51596642016-09-21 18:56:12 +08006432 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006433 }
6434
Rex Xu2bbbe062016-08-23 15:41:05 +08006435 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006436 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006437
6438 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006439 case glslang::EOpMinInvocationsNonUniform:
6440 case glslang::EOpMaxInvocationsNonUniform:
6441 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006442 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6443 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6444 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6445 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6446 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6447 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6448 if (op == glslang::EOpMinInvocationsNonUniform ||
6449 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6450 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006451 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006452 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006453 else {
6454 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006455 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006456 else
Rex Xu51596642016-09-21 18:56:12 +08006457 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006458 }
6459 }
Rex Xu430ef402016-10-14 17:22:23 +08006460 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6461 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6462 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006463 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006464 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006465 else {
6466 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006467 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006468 else
Rex Xu51596642016-09-21 18:56:12 +08006469 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006470 }
6471 }
6472 else {
6473 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006474 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006475 else
Rex Xu51596642016-09-21 18:56:12 +08006476 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006477 }
6478
Rex Xu2bbbe062016-08-23 15:41:05 +08006479 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006480 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006481
6482 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006483#endif
John Kessenich91cef522016-05-05 16:45:40 -06006484 default:
6485 logger->missingFunctionality("invocation operation");
6486 return spv::NoResult;
6487 }
Rex Xu51596642016-09-21 18:56:12 +08006488
6489 assert(opCode != spv::OpNop);
6490 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006491}
6492
Rex Xu2bbbe062016-08-23 15:41:05 +08006493// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006494spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6495 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006496{
Rex Xub7072052016-09-26 15:53:40 +08006497#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006498 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6499 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006500 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006501 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006502 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6503 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6504 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006505#else
6506 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6507 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006508 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6509 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006510#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006511
6512 // Handle group invocation operations scalar by scalar.
6513 // The result type is the same type as the original type.
6514 // The algorithm is to:
6515 // - break the vector into scalars
6516 // - apply the operation to each scalar
6517 // - make a vector out the scalar results
6518
6519 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006520 int numComponents = builder.getNumComponents(operands[0]);
6521 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006522 std::vector<spv::Id> results;
6523
6524 // do each scalar op
6525 for (int comp = 0; comp < numComponents; ++comp) {
6526 std::vector<unsigned int> indexes;
6527 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006528 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6529 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006530 if (op == spv::OpSubgroupReadInvocationKHR) {
6531 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006532 spv::IdImmediate operand = { true, operands[1] };
6533 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006534 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006535 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6536 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006537 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006538 spv::IdImmediate operand = { true, operands[1] };
6539 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006540 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006541 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6542 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006543 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006544 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006545 spvGroupOperands.push_back(scalar);
6546 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006547
Rex Xub7072052016-09-26 15:53:40 +08006548 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006549 }
6550
6551 // put the pieces together
6552 return builder.createCompositeConstruct(typeId, results);
6553}
Rex Xu2bbbe062016-08-23 15:41:05 +08006554
John Kessenich66011cb2018-03-06 16:12:04 -07006555// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006556spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6557 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006558{
6559 // Add the required capabilities.
6560 switch (op) {
6561 case glslang::EOpSubgroupElect:
6562 builder.addCapability(spv::CapabilityGroupNonUniform);
6563 break;
6564 case glslang::EOpSubgroupAll:
6565 case glslang::EOpSubgroupAny:
6566 case glslang::EOpSubgroupAllEqual:
6567 builder.addCapability(spv::CapabilityGroupNonUniform);
6568 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6569 break;
6570 case glslang::EOpSubgroupBroadcast:
6571 case glslang::EOpSubgroupBroadcastFirst:
6572 case glslang::EOpSubgroupBallot:
6573 case glslang::EOpSubgroupInverseBallot:
6574 case glslang::EOpSubgroupBallotBitExtract:
6575 case glslang::EOpSubgroupBallotBitCount:
6576 case glslang::EOpSubgroupBallotInclusiveBitCount:
6577 case glslang::EOpSubgroupBallotExclusiveBitCount:
6578 case glslang::EOpSubgroupBallotFindLSB:
6579 case glslang::EOpSubgroupBallotFindMSB:
6580 builder.addCapability(spv::CapabilityGroupNonUniform);
6581 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6582 break;
6583 case glslang::EOpSubgroupShuffle:
6584 case glslang::EOpSubgroupShuffleXor:
6585 builder.addCapability(spv::CapabilityGroupNonUniform);
6586 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6587 break;
6588 case glslang::EOpSubgroupShuffleUp:
6589 case glslang::EOpSubgroupShuffleDown:
6590 builder.addCapability(spv::CapabilityGroupNonUniform);
6591 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6592 break;
6593 case glslang::EOpSubgroupAdd:
6594 case glslang::EOpSubgroupMul:
6595 case glslang::EOpSubgroupMin:
6596 case glslang::EOpSubgroupMax:
6597 case glslang::EOpSubgroupAnd:
6598 case glslang::EOpSubgroupOr:
6599 case glslang::EOpSubgroupXor:
6600 case glslang::EOpSubgroupInclusiveAdd:
6601 case glslang::EOpSubgroupInclusiveMul:
6602 case glslang::EOpSubgroupInclusiveMin:
6603 case glslang::EOpSubgroupInclusiveMax:
6604 case glslang::EOpSubgroupInclusiveAnd:
6605 case glslang::EOpSubgroupInclusiveOr:
6606 case glslang::EOpSubgroupInclusiveXor:
6607 case glslang::EOpSubgroupExclusiveAdd:
6608 case glslang::EOpSubgroupExclusiveMul:
6609 case glslang::EOpSubgroupExclusiveMin:
6610 case glslang::EOpSubgroupExclusiveMax:
6611 case glslang::EOpSubgroupExclusiveAnd:
6612 case glslang::EOpSubgroupExclusiveOr:
6613 case glslang::EOpSubgroupExclusiveXor:
6614 builder.addCapability(spv::CapabilityGroupNonUniform);
6615 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6616 break;
6617 case glslang::EOpSubgroupClusteredAdd:
6618 case glslang::EOpSubgroupClusteredMul:
6619 case glslang::EOpSubgroupClusteredMin:
6620 case glslang::EOpSubgroupClusteredMax:
6621 case glslang::EOpSubgroupClusteredAnd:
6622 case glslang::EOpSubgroupClusteredOr:
6623 case glslang::EOpSubgroupClusteredXor:
6624 builder.addCapability(spv::CapabilityGroupNonUniform);
6625 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6626 break;
6627 case glslang::EOpSubgroupQuadBroadcast:
6628 case glslang::EOpSubgroupQuadSwapHorizontal:
6629 case glslang::EOpSubgroupQuadSwapVertical:
6630 case glslang::EOpSubgroupQuadSwapDiagonal:
6631 builder.addCapability(spv::CapabilityGroupNonUniform);
6632 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6633 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006634#ifdef NV_EXTENSIONS
6635 case glslang::EOpSubgroupPartitionedAdd:
6636 case glslang::EOpSubgroupPartitionedMul:
6637 case glslang::EOpSubgroupPartitionedMin:
6638 case glslang::EOpSubgroupPartitionedMax:
6639 case glslang::EOpSubgroupPartitionedAnd:
6640 case glslang::EOpSubgroupPartitionedOr:
6641 case glslang::EOpSubgroupPartitionedXor:
6642 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6643 case glslang::EOpSubgroupPartitionedInclusiveMul:
6644 case glslang::EOpSubgroupPartitionedInclusiveMin:
6645 case glslang::EOpSubgroupPartitionedInclusiveMax:
6646 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6647 case glslang::EOpSubgroupPartitionedInclusiveOr:
6648 case glslang::EOpSubgroupPartitionedInclusiveXor:
6649 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6650 case glslang::EOpSubgroupPartitionedExclusiveMul:
6651 case glslang::EOpSubgroupPartitionedExclusiveMin:
6652 case glslang::EOpSubgroupPartitionedExclusiveMax:
6653 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6654 case glslang::EOpSubgroupPartitionedExclusiveOr:
6655 case glslang::EOpSubgroupPartitionedExclusiveXor:
6656 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6657 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6658 break;
6659#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006660 default: assert(0 && "Unhandled subgroup operation!");
6661 }
6662
6663 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6664 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6665 const bool isBool = typeProxy == glslang::EbtBool;
6666
6667 spv::Op opCode = spv::OpNop;
6668
6669 // Figure out which opcode to use.
6670 switch (op) {
6671 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6672 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6673 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6674 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6675 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6676 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6677 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6678 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6679 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6680 case glslang::EOpSubgroupBallotBitCount:
6681 case glslang::EOpSubgroupBallotInclusiveBitCount:
6682 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6683 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6684 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6685 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6686 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6687 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6688 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6689 case glslang::EOpSubgroupAdd:
6690 case glslang::EOpSubgroupInclusiveAdd:
6691 case glslang::EOpSubgroupExclusiveAdd:
6692 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006693#ifdef NV_EXTENSIONS
6694 case glslang::EOpSubgroupPartitionedAdd:
6695 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6696 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6697#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006698 if (isFloat) {
6699 opCode = spv::OpGroupNonUniformFAdd;
6700 } else {
6701 opCode = spv::OpGroupNonUniformIAdd;
6702 }
6703 break;
6704 case glslang::EOpSubgroupMul:
6705 case glslang::EOpSubgroupInclusiveMul:
6706 case glslang::EOpSubgroupExclusiveMul:
6707 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006708#ifdef NV_EXTENSIONS
6709 case glslang::EOpSubgroupPartitionedMul:
6710 case glslang::EOpSubgroupPartitionedInclusiveMul:
6711 case glslang::EOpSubgroupPartitionedExclusiveMul:
6712#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006713 if (isFloat) {
6714 opCode = spv::OpGroupNonUniformFMul;
6715 } else {
6716 opCode = spv::OpGroupNonUniformIMul;
6717 }
6718 break;
6719 case glslang::EOpSubgroupMin:
6720 case glslang::EOpSubgroupInclusiveMin:
6721 case glslang::EOpSubgroupExclusiveMin:
6722 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006723#ifdef NV_EXTENSIONS
6724 case glslang::EOpSubgroupPartitionedMin:
6725 case glslang::EOpSubgroupPartitionedInclusiveMin:
6726 case glslang::EOpSubgroupPartitionedExclusiveMin:
6727#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006728 if (isFloat) {
6729 opCode = spv::OpGroupNonUniformFMin;
6730 } else if (isUnsigned) {
6731 opCode = spv::OpGroupNonUniformUMin;
6732 } else {
6733 opCode = spv::OpGroupNonUniformSMin;
6734 }
6735 break;
6736 case glslang::EOpSubgroupMax:
6737 case glslang::EOpSubgroupInclusiveMax:
6738 case glslang::EOpSubgroupExclusiveMax:
6739 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006740#ifdef NV_EXTENSIONS
6741 case glslang::EOpSubgroupPartitionedMax:
6742 case glslang::EOpSubgroupPartitionedInclusiveMax:
6743 case glslang::EOpSubgroupPartitionedExclusiveMax:
6744#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006745 if (isFloat) {
6746 opCode = spv::OpGroupNonUniformFMax;
6747 } else if (isUnsigned) {
6748 opCode = spv::OpGroupNonUniformUMax;
6749 } else {
6750 opCode = spv::OpGroupNonUniformSMax;
6751 }
6752 break;
6753 case glslang::EOpSubgroupAnd:
6754 case glslang::EOpSubgroupInclusiveAnd:
6755 case glslang::EOpSubgroupExclusiveAnd:
6756 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006757#ifdef NV_EXTENSIONS
6758 case glslang::EOpSubgroupPartitionedAnd:
6759 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6760 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6761#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006762 if (isBool) {
6763 opCode = spv::OpGroupNonUniformLogicalAnd;
6764 } else {
6765 opCode = spv::OpGroupNonUniformBitwiseAnd;
6766 }
6767 break;
6768 case glslang::EOpSubgroupOr:
6769 case glslang::EOpSubgroupInclusiveOr:
6770 case glslang::EOpSubgroupExclusiveOr:
6771 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006772#ifdef NV_EXTENSIONS
6773 case glslang::EOpSubgroupPartitionedOr:
6774 case glslang::EOpSubgroupPartitionedInclusiveOr:
6775 case glslang::EOpSubgroupPartitionedExclusiveOr:
6776#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006777 if (isBool) {
6778 opCode = spv::OpGroupNonUniformLogicalOr;
6779 } else {
6780 opCode = spv::OpGroupNonUniformBitwiseOr;
6781 }
6782 break;
6783 case glslang::EOpSubgroupXor:
6784 case glslang::EOpSubgroupInclusiveXor:
6785 case glslang::EOpSubgroupExclusiveXor:
6786 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006787#ifdef NV_EXTENSIONS
6788 case glslang::EOpSubgroupPartitionedXor:
6789 case glslang::EOpSubgroupPartitionedInclusiveXor:
6790 case glslang::EOpSubgroupPartitionedExclusiveXor:
6791#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006792 if (isBool) {
6793 opCode = spv::OpGroupNonUniformLogicalXor;
6794 } else {
6795 opCode = spv::OpGroupNonUniformBitwiseXor;
6796 }
6797 break;
6798 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6799 case glslang::EOpSubgroupQuadSwapHorizontal:
6800 case glslang::EOpSubgroupQuadSwapVertical:
6801 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6802 default: assert(0 && "Unhandled subgroup operation!");
6803 }
6804
John Kessenich149afc32018-08-14 13:31:43 -06006805 // get the right Group Operation
6806 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006807 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006808 default:
6809 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006810 case glslang::EOpSubgroupBallotBitCount:
6811 case glslang::EOpSubgroupAdd:
6812 case glslang::EOpSubgroupMul:
6813 case glslang::EOpSubgroupMin:
6814 case glslang::EOpSubgroupMax:
6815 case glslang::EOpSubgroupAnd:
6816 case glslang::EOpSubgroupOr:
6817 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006818 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006819 break;
6820 case glslang::EOpSubgroupBallotInclusiveBitCount:
6821 case glslang::EOpSubgroupInclusiveAdd:
6822 case glslang::EOpSubgroupInclusiveMul:
6823 case glslang::EOpSubgroupInclusiveMin:
6824 case glslang::EOpSubgroupInclusiveMax:
6825 case glslang::EOpSubgroupInclusiveAnd:
6826 case glslang::EOpSubgroupInclusiveOr:
6827 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006828 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006829 break;
6830 case glslang::EOpSubgroupBallotExclusiveBitCount:
6831 case glslang::EOpSubgroupExclusiveAdd:
6832 case glslang::EOpSubgroupExclusiveMul:
6833 case glslang::EOpSubgroupExclusiveMin:
6834 case glslang::EOpSubgroupExclusiveMax:
6835 case glslang::EOpSubgroupExclusiveAnd:
6836 case glslang::EOpSubgroupExclusiveOr:
6837 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006838 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006839 break;
6840 case glslang::EOpSubgroupClusteredAdd:
6841 case glslang::EOpSubgroupClusteredMul:
6842 case glslang::EOpSubgroupClusteredMin:
6843 case glslang::EOpSubgroupClusteredMax:
6844 case glslang::EOpSubgroupClusteredAnd:
6845 case glslang::EOpSubgroupClusteredOr:
6846 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006847 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006848 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006849#ifdef NV_EXTENSIONS
6850 case glslang::EOpSubgroupPartitionedAdd:
6851 case glslang::EOpSubgroupPartitionedMul:
6852 case glslang::EOpSubgroupPartitionedMin:
6853 case glslang::EOpSubgroupPartitionedMax:
6854 case glslang::EOpSubgroupPartitionedAnd:
6855 case glslang::EOpSubgroupPartitionedOr:
6856 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006857 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006858 break;
6859 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6860 case glslang::EOpSubgroupPartitionedInclusiveMul:
6861 case glslang::EOpSubgroupPartitionedInclusiveMin:
6862 case glslang::EOpSubgroupPartitionedInclusiveMax:
6863 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6864 case glslang::EOpSubgroupPartitionedInclusiveOr:
6865 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006866 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006867 break;
6868 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6869 case glslang::EOpSubgroupPartitionedExclusiveMul:
6870 case glslang::EOpSubgroupPartitionedExclusiveMin:
6871 case glslang::EOpSubgroupPartitionedExclusiveMax:
6872 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6873 case glslang::EOpSubgroupPartitionedExclusiveOr:
6874 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006875 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006876 break;
6877#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006878 }
6879
John Kessenich149afc32018-08-14 13:31:43 -06006880 // build the instruction
6881 std::vector<spv::IdImmediate> spvGroupOperands;
6882
6883 // Every operation begins with the Execution Scope operand.
6884 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6885 spvGroupOperands.push_back(executionScope);
6886
6887 // Next, for all operations that use a Group Operation, push that as an operand.
6888 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006889 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006890 spvGroupOperands.push_back(groupOperand);
6891 }
6892
John Kessenich66011cb2018-03-06 16:12:04 -07006893 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006894 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6895 spv::IdImmediate operand = { true, *opIt };
6896 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006897 }
6898
6899 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006900 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006901 switch (op) {
6902 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006903 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6904 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6905 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6906 }
6907 if (directionId != spv::NoResult) {
6908 spv::IdImmediate direction = { true, directionId };
6909 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006910 }
6911
6912 return builder.createOp(opCode, typeId, spvGroupOperands);
6913}
6914
John Kessenich5e4b1242015-08-06 22:53:06 -06006915spv::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 -06006916{
John Kessenich66011cb2018-03-06 16:12:04 -07006917 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6918 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006919
John Kessenich140f3df2015-06-26 16:58:36 -06006920 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006921 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006922 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006923 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006924 spv::Id typeId0 = 0;
6925 if (consumedOperands > 0)
6926 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006927 spv::Id typeId1 = 0;
6928 if (consumedOperands > 1)
6929 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006930 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006931
6932 switch (op) {
6933 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006934 if (isFloat)
6935 libCall = spv::GLSLstd450FMin;
6936 else if (isUnsigned)
6937 libCall = spv::GLSLstd450UMin;
6938 else
6939 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006940 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006941 break;
6942 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006943 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006944 break;
6945 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006946 if (isFloat)
6947 libCall = spv::GLSLstd450FMax;
6948 else if (isUnsigned)
6949 libCall = spv::GLSLstd450UMax;
6950 else
6951 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006952 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006953 break;
6954 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006955 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006956 break;
6957 case glslang::EOpDot:
6958 opCode = spv::OpDot;
6959 break;
6960 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006961 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006962 break;
6963
6964 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006965 if (isFloat)
6966 libCall = spv::GLSLstd450FClamp;
6967 else if (isUnsigned)
6968 libCall = spv::GLSLstd450UClamp;
6969 else
6970 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006971 builder.promoteScalar(precision, operands.front(), operands[1]);
6972 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006973 break;
6974 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006975 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6976 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006977 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006978 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006979 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006980 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006981 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006982 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006983 break;
6984 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006985 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006986 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006987 break;
6988 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006989 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006990 builder.promoteScalar(precision, operands[0], operands[2]);
6991 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006992 break;
6993
6994 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006995 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006996 break;
6997 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006998 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006999 break;
7000 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007001 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007002 break;
7003 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007004 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007005 break;
7006 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007007 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007008 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007009 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007010#ifdef AMD_EXTENSIONS
7011 if (typeProxy == glslang::EbtFloat16)
7012 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7013#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007014 libCall = spv::GLSLstd450InterpolateAtSample;
7015 break;
7016 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007017#ifdef AMD_EXTENSIONS
7018 if (typeProxy == glslang::EbtFloat16)
7019 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7020#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007021 libCall = spv::GLSLstd450InterpolateAtOffset;
7022 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007023 case glslang::EOpAddCarry:
7024 opCode = spv::OpIAddCarry;
7025 typeId = builder.makeStructResultType(typeId0, typeId0);
7026 consumedOperands = 2;
7027 break;
7028 case glslang::EOpSubBorrow:
7029 opCode = spv::OpISubBorrow;
7030 typeId = builder.makeStructResultType(typeId0, typeId0);
7031 consumedOperands = 2;
7032 break;
7033 case glslang::EOpUMulExtended:
7034 opCode = spv::OpUMulExtended;
7035 typeId = builder.makeStructResultType(typeId0, typeId0);
7036 consumedOperands = 2;
7037 break;
7038 case glslang::EOpIMulExtended:
7039 opCode = spv::OpSMulExtended;
7040 typeId = builder.makeStructResultType(typeId0, typeId0);
7041 consumedOperands = 2;
7042 break;
7043 case glslang::EOpBitfieldExtract:
7044 if (isUnsigned)
7045 opCode = spv::OpBitFieldUExtract;
7046 else
7047 opCode = spv::OpBitFieldSExtract;
7048 break;
7049 case glslang::EOpBitfieldInsert:
7050 opCode = spv::OpBitFieldInsert;
7051 break;
7052
7053 case glslang::EOpFma:
7054 libCall = spv::GLSLstd450Fma;
7055 break;
7056 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007057 {
7058 libCall = spv::GLSLstd450FrexpStruct;
7059 assert(builder.isPointerType(typeId1));
7060 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007061 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007062#ifdef AMD_EXTENSIONS
7063 if (width == 16)
7064 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7065 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7066#endif
Rex Xu470026f2017-03-29 17:12:40 +08007067 if (builder.getNumComponents(operands[0]) == 1)
7068 frexpIntType = builder.makeIntegerType(width, true);
7069 else
7070 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7071 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7072 consumedOperands = 1;
7073 }
John Kessenich55e7d112015-11-15 21:33:39 -07007074 break;
7075 case glslang::EOpLdexp:
7076 libCall = spv::GLSLstd450Ldexp;
7077 break;
7078
Rex Xu574ab042016-04-14 16:53:07 +08007079 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007080 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007081
John Kessenich66011cb2018-03-06 16:12:04 -07007082 case glslang::EOpSubgroupBroadcast:
7083 case glslang::EOpSubgroupBallotBitExtract:
7084 case glslang::EOpSubgroupShuffle:
7085 case glslang::EOpSubgroupShuffleXor:
7086 case glslang::EOpSubgroupShuffleUp:
7087 case glslang::EOpSubgroupShuffleDown:
7088 case glslang::EOpSubgroupClusteredAdd:
7089 case glslang::EOpSubgroupClusteredMul:
7090 case glslang::EOpSubgroupClusteredMin:
7091 case glslang::EOpSubgroupClusteredMax:
7092 case glslang::EOpSubgroupClusteredAnd:
7093 case glslang::EOpSubgroupClusteredOr:
7094 case glslang::EOpSubgroupClusteredXor:
7095 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007096#ifdef NV_EXTENSIONS
7097 case glslang::EOpSubgroupPartitionedAdd:
7098 case glslang::EOpSubgroupPartitionedMul:
7099 case glslang::EOpSubgroupPartitionedMin:
7100 case glslang::EOpSubgroupPartitionedMax:
7101 case glslang::EOpSubgroupPartitionedAnd:
7102 case glslang::EOpSubgroupPartitionedOr:
7103 case glslang::EOpSubgroupPartitionedXor:
7104 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7105 case glslang::EOpSubgroupPartitionedInclusiveMul:
7106 case glslang::EOpSubgroupPartitionedInclusiveMin:
7107 case glslang::EOpSubgroupPartitionedInclusiveMax:
7108 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7109 case glslang::EOpSubgroupPartitionedInclusiveOr:
7110 case glslang::EOpSubgroupPartitionedInclusiveXor:
7111 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7112 case glslang::EOpSubgroupPartitionedExclusiveMul:
7113 case glslang::EOpSubgroupPartitionedExclusiveMin:
7114 case glslang::EOpSubgroupPartitionedExclusiveMax:
7115 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7116 case glslang::EOpSubgroupPartitionedExclusiveOr:
7117 case glslang::EOpSubgroupPartitionedExclusiveXor:
7118#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007119 return createSubgroupOperation(op, typeId, operands, typeProxy);
7120
Rex Xu9d93a232016-05-05 12:30:44 +08007121#ifdef AMD_EXTENSIONS
7122 case glslang::EOpSwizzleInvocations:
7123 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7124 libCall = spv::SwizzleInvocationsAMD;
7125 break;
7126 case glslang::EOpSwizzleInvocationsMasked:
7127 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7128 libCall = spv::SwizzleInvocationsMaskedAMD;
7129 break;
7130 case glslang::EOpWriteInvocation:
7131 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7132 libCall = spv::WriteInvocationAMD;
7133 break;
7134
7135 case glslang::EOpMin3:
7136 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7137 if (isFloat)
7138 libCall = spv::FMin3AMD;
7139 else {
7140 if (isUnsigned)
7141 libCall = spv::UMin3AMD;
7142 else
7143 libCall = spv::SMin3AMD;
7144 }
7145 break;
7146 case glslang::EOpMax3:
7147 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7148 if (isFloat)
7149 libCall = spv::FMax3AMD;
7150 else {
7151 if (isUnsigned)
7152 libCall = spv::UMax3AMD;
7153 else
7154 libCall = spv::SMax3AMD;
7155 }
7156 break;
7157 case glslang::EOpMid3:
7158 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7159 if (isFloat)
7160 libCall = spv::FMid3AMD;
7161 else {
7162 if (isUnsigned)
7163 libCall = spv::UMid3AMD;
7164 else
7165 libCall = spv::SMid3AMD;
7166 }
7167 break;
7168
7169 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007170 if (typeProxy == glslang::EbtFloat16)
7171 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007172 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7173 libCall = spv::InterpolateAtVertexAMD;
7174 break;
7175#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007176 case glslang::EOpBarrier:
7177 {
7178 // This is for the extended controlBarrier function, with four operands.
7179 // The unextended barrier() goes through createNoArgOperation.
7180 assert(operands.size() == 4);
7181 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7182 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7183 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7184 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7185 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7186 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7187 }
7188 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7189 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7190 }
7191 return 0;
7192 }
7193 break;
7194 case glslang::EOpMemoryBarrier:
7195 {
7196 // This is for the extended memoryBarrier function, with three operands.
7197 // The unextended memoryBarrier() goes through createNoArgOperation.
7198 assert(operands.size() == 3);
7199 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7200 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7201 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7202 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7203 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7204 }
7205 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7206 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7207 }
7208 return 0;
7209 }
7210 break;
Chao Chen3c366992018-09-19 11:41:59 -07007211
7212#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007213 case glslang::EOpReportIntersectionNV:
7214 {
7215 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007216 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007217 }
7218 break;
7219 case glslang::EOpTraceNV:
7220 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007221 builder.createNoResultOp(spv::OpTraceNV, operands);
7222 return 0;
7223 }
7224 break;
7225 case glslang::EOpExecuteCallableNV:
7226 {
7227 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007228 return 0;
7229 }
7230 break;
Chao Chen3c366992018-09-19 11:41:59 -07007231 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7232 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7233 return 0;
7234#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007235 case glslang::EOpCooperativeMatrixMulAdd:
7236 opCode = spv::OpCooperativeMatrixMulAddNV;
7237 break;
7238
John Kessenich140f3df2015-06-26 16:58:36 -06007239 default:
7240 return 0;
7241 }
7242
7243 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007244 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007245 // Use an extended instruction from the standard library.
7246 // Construct the call arguments, without modifying the original operands vector.
7247 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7248 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007249 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007250 } else if (opCode == spv::OpDot && !isFloat) {
7251 // int dot(int, int)
7252 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7253 const int componentCount = builder.getNumComponents(operands[0]);
7254 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7255 builder.setPrecision(mulOp, precision);
7256 id = builder.createCompositeExtract(mulOp, typeId, 0);
7257 for (int i = 1; i < componentCount; ++i) {
7258 builder.setPrecision(id, precision);
7259 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7260 }
John Kessenich2359bd02015-12-06 19:29:11 -07007261 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007262 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007263 case 0:
7264 // should all be handled by visitAggregate and createNoArgOperation
7265 assert(0);
7266 return 0;
7267 case 1:
7268 // should all be handled by createUnaryOperation
7269 assert(0);
7270 return 0;
7271 case 2:
7272 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7273 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007274 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007275 // anything 3 or over doesn't have l-value operands, so all should be consumed
7276 assert(consumedOperands == operands.size());
7277 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007278 break;
7279 }
7280 }
7281
John Kessenich55e7d112015-11-15 21:33:39 -07007282 // Decode the return types that were structures
7283 switch (op) {
7284 case glslang::EOpAddCarry:
7285 case glslang::EOpSubBorrow:
7286 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7287 id = builder.createCompositeExtract(id, typeId0, 0);
7288 break;
7289 case glslang::EOpUMulExtended:
7290 case glslang::EOpIMulExtended:
7291 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7292 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7293 break;
7294 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007295 {
7296 assert(operands.size() == 2);
7297 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7298 // "exp" is floating-point type (from HLSL intrinsic)
7299 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7300 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7301 builder.createStore(member1, operands[1]);
7302 } else
7303 // "exp" is integer type (from GLSL built-in function)
7304 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7305 id = builder.createCompositeExtract(id, typeId0, 0);
7306 }
John Kessenich55e7d112015-11-15 21:33:39 -07007307 break;
7308 default:
7309 break;
7310 }
7311
John Kessenich32cfd492016-02-02 12:37:46 -07007312 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007313}
7314
Rex Xu9d93a232016-05-05 12:30:44 +08007315// Intrinsics with no arguments (or no return value, and no precision).
7316spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007317{
Jeff Bolz36831c92018-09-05 10:11:41 -05007318 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7319 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007320
7321 switch (op) {
7322 case glslang::EOpEmitVertex:
7323 builder.createNoResultOp(spv::OpEmitVertex);
7324 return 0;
7325 case glslang::EOpEndPrimitive:
7326 builder.createNoResultOp(spv::OpEndPrimitive);
7327 return 0;
7328 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007329 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007330 if (glslangIntermediate->usingVulkanMemoryModel()) {
7331 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7332 spv::MemorySemanticsOutputMemoryKHRMask |
7333 spv::MemorySemanticsAcquireReleaseMask);
7334 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7335 } else {
7336 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7337 }
John Kessenich82979362017-12-11 04:02:24 -07007338 } else {
7339 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7340 spv::MemorySemanticsWorkgroupMemoryMask |
7341 spv::MemorySemanticsAcquireReleaseMask);
7342 }
John Kessenich140f3df2015-06-26 16:58:36 -06007343 return 0;
7344 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007345 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7346 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007347 return 0;
7348 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007349 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7350 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007351 return 0;
7352 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007353 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7354 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007355 return 0;
7356 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007357 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7358 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007359 return 0;
7360 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007361 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7362 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007363 return 0;
7364 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007365 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7366 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007367 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007368 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007369 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007370 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007371 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007372 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007373 case glslang::EOpDeviceMemoryBarrier:
7374 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7375 spv::MemorySemanticsImageMemoryMask |
7376 spv::MemorySemanticsAcquireReleaseMask);
7377 return 0;
7378 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7379 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7380 spv::MemorySemanticsImageMemoryMask |
7381 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007382 return 0;
7383 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007384 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7385 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007386 return 0;
7387 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007388 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7389 spv::MemorySemanticsWorkgroupMemoryMask |
7390 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007391 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007392 case glslang::EOpSubgroupBarrier:
7393 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7394 spv::MemorySemanticsAcquireReleaseMask);
7395 return spv::NoResult;
7396 case glslang::EOpSubgroupMemoryBarrier:
7397 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7398 spv::MemorySemanticsAcquireReleaseMask);
7399 return spv::NoResult;
7400 case glslang::EOpSubgroupMemoryBarrierBuffer:
7401 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7402 spv::MemorySemanticsAcquireReleaseMask);
7403 return spv::NoResult;
7404 case glslang::EOpSubgroupMemoryBarrierImage:
7405 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7406 spv::MemorySemanticsAcquireReleaseMask);
7407 return spv::NoResult;
7408 case glslang::EOpSubgroupMemoryBarrierShared:
7409 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7410 spv::MemorySemanticsAcquireReleaseMask);
7411 return spv::NoResult;
7412 case glslang::EOpSubgroupElect: {
7413 std::vector<spv::Id> operands;
7414 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7415 }
Rex Xu9d93a232016-05-05 12:30:44 +08007416#ifdef AMD_EXTENSIONS
7417 case glslang::EOpTime:
7418 {
7419 std::vector<spv::Id> args; // Dummy arguments
7420 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7421 return builder.setPrecision(id, precision);
7422 }
7423#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007424#ifdef NV_EXTENSIONS
7425 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007426 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007427 return 0;
7428 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007429 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007430 return 0;
7431#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007432 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007433 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007434 return 0;
7435 }
7436}
7437
7438spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7439{
John Kessenich2f273362015-07-18 22:34:27 -06007440 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007441 spv::Id id;
7442 if (symbolValues.end() != iter) {
7443 id = iter->second;
7444 return id;
7445 }
7446
7447 // it was not found, create it
7448 id = createSpvVariable(symbol);
7449 symbolValues[symbol->getId()] = id;
7450
Rex Xuc884b4a2016-06-29 15:03:44 +08007451 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007452 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7453 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7454 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007455#ifdef NV_EXTENSIONS
7456 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7457#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007458 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007459 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007460 if (symbol->getQualifier().hasIndex())
7461 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7462 if (symbol->getQualifier().hasComponent())
7463 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007464 // atomic counters use this:
7465 if (symbol->getQualifier().hasOffset())
7466 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007467 }
7468
scygan2c864272016-05-18 18:09:17 +02007469 if (symbol->getQualifier().hasLocation())
7470 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007471 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007472 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007473 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007474 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007475 }
John Kessenich140f3df2015-06-26 16:58:36 -06007476 if (symbol->getQualifier().hasSet())
7477 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007478 else if (IsDescriptorResource(symbol->getType())) {
7479 // default to 0
7480 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7481 }
John Kessenich140f3df2015-06-26 16:58:36 -06007482 if (symbol->getQualifier().hasBinding())
7483 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007484 else if (IsDescriptorResource(symbol->getType())) {
7485 // default to 0
7486 builder.addDecoration(id, spv::DecorationBinding, 0);
7487 }
John Kessenich6c292d32016-02-15 20:58:50 -07007488 if (symbol->getQualifier().hasAttachment())
7489 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007490 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007491 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007492 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007493 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007494 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7495 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7496 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7497 }
7498 if (symbol->getQualifier().hasXfbOffset())
7499 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007500 }
7501
Rex Xu1da878f2016-02-21 20:59:01 +08007502 if (symbol->getType().isImage()) {
7503 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007504 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007505 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007506 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007507 }
7508
John Kessenich140f3df2015-06-26 16:58:36 -06007509 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007510 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007511 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007512 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007513
John Kessenich5611c6d2018-04-05 11:25:02 -06007514 // nonuniform
7515 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7516
John Kessenichecba76f2017-01-06 00:34:48 -07007517#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007518 if (builtIn == spv::BuiltInSampleMask) {
7519 spv::Decoration decoration;
7520 // GL_NV_sample_mask_override_coverage extension
7521 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007522 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007523 else
7524 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007525 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007526 if (decoration != spv::DecorationMax) {
7527 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7528 }
7529 }
chaoc771d89f2017-01-13 01:10:53 -08007530 else if (builtIn == spv::BuiltInLayer) {
7531 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007532 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007533 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007534 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7535 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7536 }
John Kessenichb41bff62017-08-11 13:07:17 -06007537 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007538 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7539 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007540 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7541 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7542 }
7543 }
7544
chaoc6e5acae2016-12-20 13:28:52 -08007545 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007546 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007547 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007548 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7549 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007550 if (symbol->getQualifier().pervertexNV) {
7551 builder.addDecoration(id, spv::DecorationPerVertexNV);
7552 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7553 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7554 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007555#endif
7556
John Kessenich5d610ee2018-03-07 18:05:55 -07007557 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7558 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7559 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7560 symbol->getType().getQualifier().semanticName);
7561 }
7562
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007563 if (symbol->getBasicType() == glslang::EbtReference) {
7564 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7565 }
7566
John Kessenich140f3df2015-06-26 16:58:36 -06007567 return id;
7568}
7569
Chao Chen3c366992018-09-19 11:41:59 -07007570#ifdef NV_EXTENSIONS
7571// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7572void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7573{
7574 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007575 if (qualifier.perPrimitiveNV) {
7576 // Need to add capability/extension for fragment shader.
7577 // Mesh shader already adds this by default.
7578 if (glslangIntermediate->getStage() == EShLangFragment) {
7579 builder.addCapability(spv::CapabilityMeshShadingNV);
7580 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7581 }
Chao Chen3c366992018-09-19 11:41:59 -07007582 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007583 }
Chao Chen3c366992018-09-19 11:41:59 -07007584 if (qualifier.perViewNV)
7585 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7586 if (qualifier.perTaskNV)
7587 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7588 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007589 if (qualifier.perPrimitiveNV) {
7590 // Need to add capability/extension for fragment shader.
7591 // Mesh shader already adds this by default.
7592 if (glslangIntermediate->getStage() == EShLangFragment) {
7593 builder.addCapability(spv::CapabilityMeshShadingNV);
7594 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7595 }
Chao Chen3c366992018-09-19 11:41:59 -07007596 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007597 }
Chao Chen3c366992018-09-19 11:41:59 -07007598 if (qualifier.perViewNV)
7599 builder.addDecoration(id, spv::DecorationPerViewNV);
7600 if (qualifier.perTaskNV)
7601 builder.addDecoration(id, spv::DecorationPerTaskNV);
7602 }
7603}
7604#endif
7605
John Kessenich55e7d112015-11-15 21:33:39 -07007606// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007607// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007608//
7609// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7610//
7611// Recursively walk the nodes. The nodes form a tree whose leaves are
7612// regular constants, which themselves are trees that createSpvConstant()
7613// recursively walks. So, this function walks the "top" of the tree:
7614// - emit specialization constant-building instructions for specConstant
7615// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007616spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007617{
John Kessenich7cc0e282016-03-20 00:46:02 -06007618 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007619
qining4f4bb812016-04-03 23:55:17 -04007620 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007621 if (! node.getQualifier().specConstant) {
7622 // hand off to the non-spec-constant path
7623 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7624 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007625 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007626 nextConst, false);
7627 }
7628
7629 // We now know we have a specialization constant to build
7630
John Kessenichd94c0032016-05-30 19:29:40 -06007631 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007632 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7633 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7634 std::vector<spv::Id> dimConstId;
7635 for (int dim = 0; dim < 3; ++dim) {
7636 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7637 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007638 if (specConst) {
7639 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7640 glslangIntermediate->getLocalSizeSpecId(dim));
7641 }
qining4f4bb812016-04-03 23:55:17 -04007642 }
7643 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7644 }
7645
7646 // An AST node labelled as specialization constant should be a symbol node.
7647 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7648 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007649 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007650 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007651 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7652 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7653 // will set the builder into spec constant op instruction generating mode.
7654 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007655 result = accessChainLoad(sub_tree->getType());
7656 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007657 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007658 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007659 } else {
7660 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007661 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007662 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007663 builder.addName(result, sn->getName().c_str());
7664 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007665 }
qining4f4bb812016-04-03 23:55:17 -04007666
7667 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7668 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007669 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007670 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007671}
7672
John Kessenich140f3df2015-06-26 16:58:36 -06007673// Use 'consts' as the flattened glslang source of scalar constants to recursively
7674// build the aggregate SPIR-V constant.
7675//
7676// If there are not enough elements present in 'consts', 0 will be substituted;
7677// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7678//
qining08408382016-03-21 09:51:37 -04007679spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007680{
7681 // vector of constants for SPIR-V
7682 std::vector<spv::Id> spvConsts;
7683
7684 // Type is used for struct and array constants
7685 spv::Id typeId = convertGlslangToSpvType(glslangType);
7686
7687 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007688 glslang::TType elementType(glslangType, 0);
7689 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007690 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007691 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007692 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007693 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007694 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007695 } else if (glslangType.isCoopMat()) {
7696 glslang::TType componentType(glslangType.getBasicType());
7697 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007698 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007699 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7700 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007701 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007702 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007703 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7704 bool zero = nextConst >= consts.size();
7705 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007706 case glslang::EbtInt8:
7707 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7708 break;
7709 case glslang::EbtUint8:
7710 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7711 break;
7712 case glslang::EbtInt16:
7713 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7714 break;
7715 case glslang::EbtUint16:
7716 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7717 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007718 case glslang::EbtInt:
7719 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7720 break;
7721 case glslang::EbtUint:
7722 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7723 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007724 case glslang::EbtInt64:
7725 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7726 break;
7727 case glslang::EbtUint64:
7728 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7729 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007730 case glslang::EbtFloat:
7731 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7732 break;
7733 case glslang::EbtDouble:
7734 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7735 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007736 case glslang::EbtFloat16:
7737 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7738 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007739 case glslang::EbtBool:
7740 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7741 break;
7742 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007743 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007744 break;
7745 }
7746 ++nextConst;
7747 }
7748 } else {
7749 // we have a non-aggregate (scalar) constant
7750 bool zero = nextConst >= consts.size();
7751 spv::Id scalar = 0;
7752 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007753 case glslang::EbtInt8:
7754 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7755 break;
7756 case glslang::EbtUint8:
7757 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7758 break;
7759 case glslang::EbtInt16:
7760 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7761 break;
7762 case glslang::EbtUint16:
7763 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7764 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007765 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007766 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007767 break;
7768 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007769 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007770 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007771 case glslang::EbtInt64:
7772 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7773 break;
7774 case glslang::EbtUint64:
7775 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7776 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007777 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007778 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007779 break;
7780 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007781 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007782 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007783 case glslang::EbtFloat16:
7784 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7785 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007786 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007787 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007788 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007789 case glslang::EbtReference:
7790 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7791 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7792 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007793 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007794 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007795 break;
7796 }
7797 ++nextConst;
7798 return scalar;
7799 }
7800
7801 return builder.makeCompositeConstant(typeId, spvConsts);
7802}
7803
John Kessenich7c1aa102015-10-15 13:29:11 -06007804// Return true if the node is a constant or symbol whose reading has no
7805// non-trivial observable cost or effect.
7806bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7807{
7808 // don't know what this is
7809 if (node == nullptr)
7810 return false;
7811
7812 // a constant is safe
7813 if (node->getAsConstantUnion() != nullptr)
7814 return true;
7815
7816 // not a symbol means non-trivial
7817 if (node->getAsSymbolNode() == nullptr)
7818 return false;
7819
7820 // a symbol, depends on what's being read
7821 switch (node->getType().getQualifier().storage) {
7822 case glslang::EvqTemporary:
7823 case glslang::EvqGlobal:
7824 case glslang::EvqIn:
7825 case glslang::EvqInOut:
7826 case glslang::EvqConst:
7827 case glslang::EvqConstReadOnly:
7828 case glslang::EvqUniform:
7829 return true;
7830 default:
7831 return false;
7832 }
qining25262b32016-05-06 17:25:16 -04007833}
John Kessenich7c1aa102015-10-15 13:29:11 -06007834
7835// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007836// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007837// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007838// Return true if trivial.
7839bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7840{
7841 if (node == nullptr)
7842 return false;
7843
John Kessenich84cc15f2017-05-24 16:44:47 -06007844 // count non scalars as trivial, as well as anything coming from HLSL
7845 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007846 return true;
7847
John Kessenich7c1aa102015-10-15 13:29:11 -06007848 // symbols and constants are trivial
7849 if (isTrivialLeaf(node))
7850 return true;
7851
7852 // otherwise, it needs to be a simple operation or one or two leaf nodes
7853
7854 // not a simple operation
7855 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7856 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7857 if (binaryNode == nullptr && unaryNode == nullptr)
7858 return false;
7859
7860 // not on leaf nodes
7861 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7862 return false;
7863
7864 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7865 return false;
7866 }
7867
7868 switch (node->getAsOperator()->getOp()) {
7869 case glslang::EOpLogicalNot:
7870 case glslang::EOpConvIntToBool:
7871 case glslang::EOpConvUintToBool:
7872 case glslang::EOpConvFloatToBool:
7873 case glslang::EOpConvDoubleToBool:
7874 case glslang::EOpEqual:
7875 case glslang::EOpNotEqual:
7876 case glslang::EOpLessThan:
7877 case glslang::EOpGreaterThan:
7878 case glslang::EOpLessThanEqual:
7879 case glslang::EOpGreaterThanEqual:
7880 case glslang::EOpIndexDirect:
7881 case glslang::EOpIndexDirectStruct:
7882 case glslang::EOpLogicalXor:
7883 case glslang::EOpAny:
7884 case glslang::EOpAll:
7885 return true;
7886 default:
7887 return false;
7888 }
7889}
7890
7891// Emit short-circuiting code, where 'right' is never evaluated unless
7892// the left side is true (for &&) or false (for ||).
7893spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7894{
7895 spv::Id boolTypeId = builder.makeBoolType();
7896
7897 // emit left operand
7898 builder.clearAccessChain();
7899 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007900 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007901
7902 // Operands to accumulate OpPhi operands
7903 std::vector<spv::Id> phiOperands;
7904 // accumulate left operand's phi information
7905 phiOperands.push_back(leftId);
7906 phiOperands.push_back(builder.getBuildPoint()->getId());
7907
7908 // Make the two kinds of operation symmetric with a "!"
7909 // || => emit "if (! left) result = right"
7910 // && => emit "if ( left) result = right"
7911 //
7912 // TODO: this runtime "not" for || could be avoided by adding functionality
7913 // to 'builder' to have an "else" without an "then"
7914 if (op == glslang::EOpLogicalOr)
7915 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7916
7917 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007918 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007919
7920 // emit right operand as the "then" part of the "if"
7921 builder.clearAccessChain();
7922 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007923 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007924
7925 // accumulate left operand's phi information
7926 phiOperands.push_back(rightId);
7927 phiOperands.push_back(builder.getBuildPoint()->getId());
7928
7929 // finish the "if"
7930 ifBuilder.makeEndIf();
7931
7932 // phi together the two results
7933 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7934}
7935
Frank Henigman541f7bb2018-01-16 00:18:26 -05007936#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007937// Return type Id of the imported set of extended instructions corresponds to the name.
7938// Import this set if it has not been imported yet.
7939spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7940{
7941 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7942 return extBuiltinMap[name];
7943 else {
Rex Xu51596642016-09-21 18:56:12 +08007944 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007945 spv::Id extBuiltins = builder.import(name);
7946 extBuiltinMap[name] = extBuiltins;
7947 return extBuiltins;
7948 }
7949}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007950#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007951
John Kessenich140f3df2015-06-26 16:58:36 -06007952}; // end anonymous namespace
7953
7954namespace glslang {
7955
John Kessenich68d78fd2015-07-12 19:28:10 -06007956void GetSpirvVersion(std::string& version)
7957{
John Kessenich9e55f632015-07-15 10:03:39 -06007958 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007959 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007960 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007961 version = buf;
7962}
7963
John Kessenicha372a3e2017-11-02 22:32:14 -06007964// For low-order part of the generator's magic number. Bump up
7965// when there is a change in the style (e.g., if SSA form changes,
7966// or a different instruction sequence to do something gets used).
7967int GetSpirvGeneratorVersion()
7968{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007969 // return 1; // start
7970 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007971 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007972 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007973 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007974 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7975 // versions 4 and 6 each generate OpArrayLength as it has long been done
7976 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007977}
7978
John Kessenich140f3df2015-06-26 16:58:36 -06007979// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007980void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007981{
7982 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007983 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007984 if (out.fail())
7985 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007986 for (int i = 0; i < (int)spirv.size(); ++i) {
7987 unsigned int word = spirv[i];
7988 out.write((const char*)&word, 4);
7989 }
7990 out.close();
7991}
7992
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007993// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007994void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007995{
7996 std::ofstream out;
7997 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007998 if (out.fail())
7999 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008000 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008001 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008002 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008003 if (varName != nullptr) {
8004 out << "\t #pragma once" << std::endl;
8005 out << "const uint32_t " << varName << "[] = {" << std::endl;
8006 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008007 const int WORDS_PER_LINE = 8;
8008 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8009 out << "\t";
8010 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8011 const unsigned int word = spirv[i + j];
8012 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8013 if (i + j + 1 < (int)spirv.size()) {
8014 out << ",";
8015 }
8016 }
8017 out << std::endl;
8018 }
Flavio15017db2017-02-15 14:29:33 -08008019 if (varName != nullptr) {
8020 out << "};";
8021 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008022 out.close();
8023}
8024
John Kessenich140f3df2015-06-26 16:58:36 -06008025//
8026// Set up the glslang traversal
8027//
John Kessenich4e11b612018-08-30 16:56:59 -06008028void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008029{
Lei Zhang17535f72016-05-04 15:55:59 -04008030 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008031 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008032}
8033
John Kessenich4e11b612018-08-30 16:56:59 -06008034void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008035 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008036{
John Kessenich140f3df2015-06-26 16:58:36 -06008037 TIntermNode* root = intermediate.getTreeRoot();
8038
8039 if (root == 0)
8040 return;
8041
John Kessenich4e11b612018-08-30 16:56:59 -06008042 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008043 if (options == nullptr)
8044 options = &defaultOptions;
8045
John Kessenich4e11b612018-08-30 16:56:59 -06008046 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008047
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008048 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008049 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008050 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008051 it.dumpSpv(spirv);
8052
GregFfb03a552018-03-29 11:49:14 -06008053#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008054 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8055 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008056 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008057 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008058
John Kessenich4e11b612018-08-30 16:56:59 -06008059 if (options->validate)
8060 SpirvToolsValidate(intermediate, spirv, logger);
8061
John Kessenich717c80a2018-08-23 15:17:10 -06008062 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008063 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008064
GregFcd1f1692017-09-21 18:40:22 -06008065#endif
8066
John Kessenich4e11b612018-08-30 16:56:59 -06008067 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008068}
8069
8070}; // end namespace glslang